javascript – jQuery .data()与.html()

参见英文答案 >
Unable to set data attribute using jQuery Data() API                                    7个

奇怪的问题 – 也许我错过了什么.

我的代码:

HTML

<div id="container">
    <span data-foo="initial content">Blabla</span>    
</div>

jQuery的

console.log($("span").data("foo")); //initial content
console.log($("#container").html()); //<span data-foo="initial content">Blabla</span>   

$("span").data("foo", "new content");

console.log($("span").data("foo")); //new content
console.log($("#container").html()); //<span data-foo="initial content">Blabla</span>   <----- ?!?!?!?!

最后一行显示了意外行为.之前由.data(“foo”,“new content”)完成的修改并不反映通过.html()读取内容的时间

小提琴:
http://jsfiddle.net/sSZjh/

最佳答案 jQuery中的.data只读取数据属性,但不设置它们.您需要使用.attr(‘data -…’)来设置数据属性.

As of jQuery 1.4.3 HTML 5 data- attributes will be automatically pulled in to jQuery’s data object. The treatment of attributes with embedded dashes was changed in jQuery 1.6 to conform to the W3C HTML5 specification.

http://api.jquery.com/data/

点赞