简体   繁体   English

Jquery Data属性选择器不起作用

[英]Jquery Data attribute selector not working

I have this element 我有这个元素

<div class="messages selected" data-conversationId=""></div>

The data-attribute conversationId is set dynamically like so: data-attribute conversationId动态设置如下:

$(".messages").data("conversationId", conversationId);

I am having issues using a selector to select this element by the data attribute. 我在使用选择器通过data属性选择此元素时遇到问题。

$(".messages[data-conversationId=4]")

Returns empty array. 返回空数组。 Interestingly: 有趣的是:

$(".messages").data("conversationId")

returns 4 返回4

What is wrong with my selector? 我的选择器出了什么问题?

If you set your dynamic attribute via jquery's .data() you will have the above problem. 如果通过jquery的.data()设置动态属性,则会出现上述问题。

However, if you set the dynamic attribute via jquery's .attr() method, you won't have this problem 但是,如果通过jquery的.attr()方法设置动态属性,则不会出现此问题

Example here: https://jsfiddle.net/6dn5wjL8/8/ 示例: https//jsfiddle.net/6dn5wjL8/8/

HTML HTML

<div id="test1" class="messages selected" data-conversationId="">testContent1</div>
<div id="test2" class="messages selected" data-conversationId="">testContent2</div>

JS: JS:

// Will work
$("#test1").attr("data-conversationId", 4)
// Will not work
$("#test2").data("conversationId", 3)


alert("With selector .messages[data-conversationId=4] I found a div with this content: "+$(".messages[data-conversationId=4]").html())

alert("With selector .messages[data-conversationId=3] I found a div with this content: "+$(".messages[data-conversationId=3]").html())

I think with this statement $('.message[data-conversationId=4]') , you are trying to select an element which has class message and who has data-conversationId as 4. 我认为使用此语句$('。message [data-conversationId = 4]'),您正在尝试选择具有类消息且data-conversationId为4的元素。

and this statement $(".message").data('conversationId'), in this example of yours would return undefined because in the markup you have mentioned it as data-conversationid="" 这个语句$(“。message”)。data('conversationId'),在你的这个例子中将返回undefined,因为在标记中你提到它为data-conversationid =“”

change the markup to data-conversationid="5" and check with the statement $(".message").data('conversationId'),it would return 5 将标记更改为data-conversationid =“5”并使用语句$(“。message”)。data('conversationId')进行检查,它将返回5

Hope this helps 希望这可以帮助

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

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