简体   繁体   English

带有输入选择器的jquery数据属性在循环中

[英]jquery data attribute with input selector in a loop

I have an html table built from a database query which loops through and creates a button for each camera name found and puts them in a table: 我有一个通过数据库查询构建的html表,该查询循环遍历并为找到的每个摄像机名称创建一个按钮,并将它们放在表中:

<?php
for($i=0;$i<$num_rows;$i++)
{

?>
<tr>
<td>
    <input type="submit" class="play" data-hash="<?php echo $result_cameras[$i]["camera_hash"]; ?>" value="<?php echo $result_cameras[$i]["camera_name"]; ?>">
</td>
</tr>

<?php
}
?>

This resolves to something like this: 可以解决如下问题:

<tr>
<td>
    <input type="submit" class="play" data-hash="0d3d0ac6e54a640c73f1149d4d0bbc38e99d10f5" value="Office Window">
</td>
</tr>
<tr>
<td>
    <input type="submit" class="play" data-hash="b824cba374c3d5ab7806ad8260c939323c03147b" value="aaa">
</td>
</tr>
<tr>
<td>
    <input type="submit" class="play" data-hash="ec9658f0c1855e2e2ac09ae284f5e6990dbf445d" value="laptop">
</td>
</tr>

Notice the data hash attribute is different for each button. 请注意,每个按钮的数据哈希属性都不同。 I want to process this button with my jquery code: 我想用我的jQuery代码处理此按钮:

$(".play").click(function(){
    var camerahash = $('input').data('hash');
    console.log($('input').data('hash'));
});

No matter which button I click I will always get the hash from the first button I click: 0d3d0ac6e54a640c73f1149d4d0bbc38e99d10f5 . 无论单击哪个按钮,我总是会从单击的第一个按钮获得哈希值: 0d3d0ac6e54a640c73f1149d4d0bbc38e99d10f5 Any help is appreciated. 任何帮助表示赞赏。

$('input').data('hash')为您提供选择中第一个输入的data属性,使用$(this).data('hash')获得当前单击的输入的data属性

You need to specify which input element to read. 您需要指定要读取的输入元素。 Try something like: 尝试类似:

$(".play").click(function(){
    $this = $(this);
    var camerahash = $this.data('hash');
    console.log($this.data('hash'));
});

You are always calling the first object of .play. 您总是在调用.play的第一个对象。 This would be a correct way: 这是正确的方法:

$('.play').on('click', function(){

  var camerahash = $(this).data('hash');

});

You could always grab them by using the .attr(data-hash) html5 attribute. 您始终可以使用.attr(data-hash) html5属性来获取它们。

Try: 尝试:

$('.play').on('click', function() {
      var _hash = $(this).attr('data-hash');
      console.log(_hash);
});

Your selector will return the first one that it comes to. 您的选择器将返回它涉及的第一个。 Use this instead 改用这个

<script>
    $("input.play").click(function() {
        alert($(this).data('hash'));
    });
</script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM