TL;博士
$(".href").each(function()
{
console.log($(this).attr("data-id"));
});
说明
你的代码运行和工作,只是你不觉得它的工作方式。
让我们假设$length
等于2
(其实并不重要):
$length = 2;
for($x = 0; $x < $length; $x++)
{
echo "<button ><a class='href' data-id='$x'>Text</a></button>";
}
它将产生两个按钮,一个id为0
,一个ID为1
:
<button ><a class='href' data-id='0'>Text</a></button>
<button ><a class='href' data-id='1'>Text</a></button>
您正试图获取像这样的值:
$y = $('.href').attr('data-id');
然而,它确实如中所解释的only fetches the data-id matching the first element which has class 'href'。
如果你希望获得当前点击的按钮id
那么你可以做这样的:
$('.href').on("click", function()
{
var clickedId = $(this).attr('data-id');
});
(听点击与href
类的元素事件)
Working demo
如果你想获得所有可用的ID,那么你可以通过其中的每一个,并获得ID:
<p id="output"></p>
$(".href").each(function()
{
var currentId = $(this).attr("data-id");
$("#output").append("Button id: " + currentId + "<br />");
});
(通过其具有类href
元素的每个实例解析)
Working demo
你不是应该使用串联为字符串?即:data-id ='“。$ x。”'> .......? – remixdesign 2014-10-20 20:48:20
@remixdesign不需要PHP。 – Jonast92 2014-10-20 20:48:56
PHP将解析双引号内的变量,@remixdesign – smerny 2014-10-20 20:49:40