我试图将参数从 HTML 传递到 jQuery,但是即使我在 php 文件中使用如下所示的 for 循环,我也只得到 1 种类型的答案:
for ($x = 0; $x < $length; $x++) {
echo "<button ><a class='href' data-id='$x'>Text</a></button>";
}
我像这样检索它:
$y = $('.href').attr('data-id');
是不是我哪里做得不对?
最佳答案
来自http://api.jquery.com/attr/ :
Get the value of an attribute for the first element in the set
(强调)
也就是说,即使 $('.href')
匹配 $length
元素,它也只给出 0
。
同样来自文档,
To get the value for each element individually, use a looping construct such as jQuery's
.each()
or.map()
method.
(其他人都在发布代码示例,所以......)
var y = $('.href').map(function (index, element) {
return $(element).attr('data-id');
}).get();
关于javascript - 将参数从 html 传递到 jquery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26474600/