[英]why that my button only give me the value of my first column inside a table
why that my button only give me the value of my first column inside a table when i clicked the other button it give me the same output as the first column.为什么当我单击另一个按钮时,我的按钮只给我表格内第一列的值,它给我与第一列相同的输出。 here is the code in showing the item inside the table
这是显示表格内项目的代码
try { while($row=$query->fetch(PDO::FETCH_NUM)) { echo '<tr> <td ><div id="studID">'.$row[0].'</div></td> <td>'.$row[1].'</td> <td>'.$row[2].'</td> <td>'.$row[3].'</td> <td> <button class="button active" name="button"value="'.$row[0].'">view</button> </td> </tr>'; } echo '</table>'; } catch(PDOException $e ){ echo "Error: ".$e; }
and here is the coded when i clicked the button这是我点击按钮时的编码
<script type="text/javascript"> $(".button").click(function(){ var id =$('.button').val(); alert (id); }); </script>>
thanks in advance.
Use this
object like below:像下面这样使用
this
对象:
<script type="text/javascript">
$(".button").click(function(){
var id =$(this).val();
alert (id);
});
</script>>
Click event always get first matching element from dom. Click 事件总是从 dom 中获取第一个匹配元素。 If you want to get all buttons get then by for() loop , each loop, map function, or you can follow underscore library.
如果你想获得所有按钮,那么通过 for() 循环,每个循环,映射函数,或者你可以遵循下划线库。
Don't give your button the value, instead in your click function do不要给你的按钮值,而是在你的点击功能中做
$("td").each(function() {
var id = $('td').val();
alert(id);
});
This way it will iterate over each of your td elements and produce an alert with the value of it.通过这种方式,它将遍历您的每个 td 元素并生成带有它的值的警报。 Or you can do this:
或者你可以这样做:
var valueArray
$("td").each(function() {
var id = $('td').val();
valueArray.push(id);
});
alert(valueArray);
Which should hopefully do an alert with all the values in it.希望其中的所有值都可以发出警报。
and for your button do:对于您的按钮,请执行以下操作:
<button class="button active" name="button">view</button>
But bear in mind that this will do it for all td elements on your page so if you have more than one table this will do an alert for every td in every table you have.但请记住,这将对您页面上的所有 td 元素执行此操作,因此如果您有多个表,这将对您拥有的每个表中的每个 td 发出警报。 To avoid this give the table an id and replace
$("td")
with $("#tableID td")
.为了避免这种情况,给表一个 id 并将
$("td")
替换$("td")
$("#tableID td")
。
You need to iterate through all the classes available using jQuery.each() function.您需要使用 jQuery.each() 函数遍历所有可用的类。 While here you are only fetching the first element value.
在这里,您只获取第一个元素值。
You can try something like below:您可以尝试以下操作:
<script type="text/javascript">
$(".button").click(function(){
$( ".button" ).each(function( index ) {
alert( $( this ).val() );
});
});
</script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.