2017-09-03 38 views
0

我正在从模板引擎(Template7)生成一个列表,并向每个列表项中的数据标记添加一个userID。例如从模板生成列表中获取html数据 - jQuery

<li> 
    <a id='user' data-user-id='5'> 
     <div>content here</div> 
    </a> 
</li> 
<li> 
    <a id='user' data-user-id='6'> 
     <div>content here</div> 
    </a> 
</li> 

我试图获取列表项点击使用jQuery的“用户ID”的数据,但我似乎在做,而不是越来越第一个列表项的用户ID - 在这种情况下总是5.

$(document).on("touchend", "#user", function(e) { 
    e.preventDefault(); 

    var userItem = $("#user"); 
    var userID = userItem.data("user-id"); 
    console.log(matchID); 
}); 

我在哪里出错了?每个项目的唯一ID会起作用,但那么它需要被解析等等,所以必须有更好的方法!这种事情有最佳做法吗?

回答

1

尝试用这种替代#user应该在你的情况下工作

ID选择总是选择第一个元素匹配的ID。建议不要使用相同ID的多个元素。尝试改为使用类名称。 任何方式为您的查询,您可以使用下面的代码。

$(document).on("touchend", "#user", function(e) { 
     e.preventDefault(); 

     var userID = $(this).data("user-id"); 
     console.log(userID); 
    }); 
+0

'$(“#user”)。on(“touchend”,function(e){and var userID = $(this).data (“user-id”);' 试过这个,似乎也没有工作要么 – PhilS

+0

console.log现在永远不会达到 – PhilS

+0

你在控制台中得到任何错误吗? –

1

使用一个CSS类每个锚项目,像这样:

<li> 
    <a class='user' data-user-id='5'> 
     <div>content here</div> 
    </a> 
</li> 

标识属性意味着是独有的元素。

+0

中的console.log行现在永远达不到,不知道是怎么回事! – PhilS

+0

好吧,有趣的是,它只适用于用户的id,而不是类... – PhilS

1
To get the content of the attribute **data-user-id** like in <a id='user' data-user-id='5'> you have to use 

$(this).attr("data-user-id") // will return the string "5" 

or .data() (if you use newer jQuery >= 1.4.3) 

$(this).data("user-id") // will return the number 5 
+0

是的,这有效,与其他答案类似 – PhilS