[英]Cannot set data-id to HTML element
我正在尋找這個。 發現這篇舊文章和這篇 文章 。 但不適合我。
我的問題是:我無法通過jQuery將增加的data-id
設置為HTML Element。 我能夠提醒相同,但我沒有設置HTML。 如果我檢查,元素沒有變化。
jQuery的
$(document).ready(function() {
$("#search").click(function(){
var num = $(this).data('id');
num++;
$("span").text(num);
$(this).data('id', num);
});
});
我也嘗試了這個
$(this).data('id') === num;
這是一個jsFiddle演示
我正在使用v1.9.1
並且在控制台中沒有錯誤。 如果有人能找到這個問題,它會很棒。
所有其他答案都是正確的 - 將'val'
修正為val
- 這當然解決了NaN
問題。
然而問題是:
我無法通過jQuery將增加的data-id設置為HTML Element。 我能夠提醒相同,但我沒有設置HTML。 如果我檢查,元素沒有變化。
jQuery使用內部表示(1)來表示data
。 如果要在檢查器中查看data-id
,則需要使用: $(this).attr('data-id', num);
(1)“內部代表”:
所有數據都存儲在名為cache的jQuery對象的屬性中。 在控制台中記錄$ .cache的內容,以查看與任何DOM元素關聯的所有數據和事件。
問題出在這一行。
$(this).data('id', 'num');
num應該是變量,而不是字符串。
將其更改為此,它將正常工作:
$(this).data('id', num);
試試這個:
$(this).attr('data-id');
並設置attribue:
$(this).attr('data-id', num);
標准Pure Javascript data-attr
試試這個
this.dataset['id']=num;
要么
this.dataset.id=num;
根據評論編輯 ,以及為什么我不使用jaquery
這是從jquery的代碼中獲取的data-attr的部分函數。(我不使用jquery)
function dataAttr( elem, key, data ) {
var name;
// If nothing was found internally, try to fetch any
// data from the HTML5 data-* attribute
if ( data === undefined && elem.nodeType === 1 ) {
name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase();
data = elem.getAttribute( name );
if ( typeof data === "string" ) {
try {
data = data === "true" ? true :
data === "false" ? false :
data === "null" ? null :
// Only convert to a number if it doesn't change the string
+data + "" === data ? +data :
rbrace.test( data ) ? jQuery.parseJSON( data ) :
data;
} catch( e ) {}
// Make sure we set the data so it isn't changed later
data_user.set( elem, key, data );
} else {
data = undefined;
}
}
return data;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.