I have a problem defining var for button value that's dynamic. It works in php, it does not work in my javascript.
我有一个问题,为动态的按钮值定义var。它在php中工作,在javascript中不工作。
Lets say I have 3 php-echoed buttons with values 1, 2 and 3 No matter which I click, it will return value 3, even for buttons that clearly have value 1 or 2. Why? Can't figure it out.
假设我有3个php-echo按钮,值分别为1、2和3,无论我点击哪个按钮,它都会返回值3,即使是那些显然有值1或2的按钮。为什么?想不出来。
As if javascript only gets the highest or the last value of a button. I'm new to javascript so my knowledge is really small on this.
就好像javascript只获取按钮的最高值或最后值一样。我对javascript很陌生,所以我对它的了解很少。
<script type='text/javascript'>
function myFunction() {
var msg_id = document.getElementById('like').value;
var dataString = 'msg_id=' + msg_id;
$.ajax({
type: 'POST',
url: 'ajaxjs.php',
data: dataString,
cache: false,
success: function(html) {
alert(html);
}
});
}
</script>
then I have php-echoed form
然后是php-echo表单
while($row = mysql_fetch_array($msg_check)) {
$msgid = $row['id'];
echo "
<form method='POST'>
<input id='like' onclick='myFunction()' type='button' value='$msgid'>
</form>
external ajaxjs.php
外部ajaxjs.php
$msgid = $_POST['msg_id'];
echo $msgid;
1 个解决方案
#1
3
Try this :
试试这个:
while($row = mysql_fetch_array($msg_check)) {
$msgid = $row['id'];
echo "<form method='POST'>
<input data-id ="$msgid" onclick='return myFunction(this)' type='button' value='$msgid'>
</form>
}
Ajax :
Ajax:
<script type='text/javascript'>
function myFunction(obj) {
var element_id = $(obj).data('id');
var msg_id = $(obj).val();
var dataString = 'msg_id=' + msg_id;
console.log(dataString ); //see in console
$.ajax({
type: 'POST',
url: 'ajaxjs.php',
data: dataString,
cache: false,
success: function(html) {
alert(html);
}
});
}
</script>
#1
3
Try this :
试试这个:
while($row = mysql_fetch_array($msg_check)) {
$msgid = $row['id'];
echo "<form method='POST'>
<input data-id ="$msgid" onclick='return myFunction(this)' type='button' value='$msgid'>
</form>
}
Ajax :
Ajax:
<script type='text/javascript'>
function myFunction(obj) {
var element_id = $(obj).data('id');
var msg_id = $(obj).val();
var dataString = 'msg_id=' + msg_id;
console.log(dataString ); //see in console
$.ajax({
type: 'POST',
url: 'ajaxjs.php',
data: dataString,
cache: false,
success: function(html) {
alert(html);
}
});
}
</script>