[英]How to add an HTML attribute with jQuery
好吧,我有這個jQuery圖像幻燈片,它使用<a>中的屬性“control”。 看到它沒有驗證我搜索了一種通過jQuery在我的HMTL中添加這個屬性的方法,但我沒有找到任何相關的東西。 現在我並不關心我的頁面有多有效,但我真的很好奇如何在HTML標記內添加HTML屬性。
如果我對我的解釋不夠清楚,我有這個代碼:
<a id="previous" control="-6" href="#"></a>
我想用jQuery添加control =“ - 6” 。
使用jQuery的attr
函數
$("#previous").attr("control", "-6");
一個例子
// Try to retrieve the control attribute
// returns undefined because the attribute doesn't exists
$("#previous").attr("control");
// Set the control attribute
$("#previous").attr("control", "-6");
// Retrieve the control attribute (-6)
$("#previous").attr("control");
在jsFiddle上查看此示例
您也可以使用data
函數在元素上存儲值。 以相同的方式工作,例如:
$("#previous").data("control"); // undefined
$("#previous").data("control", "-6"); // set the element data
$("#previous").data("control"); // retrieve -6
使用data
可以存儲更復雜的值,如對象
$("#previos").data("control", { value: -6 });
($("#previos").data("control")).value; // -6
由於這里已經很好地介紹了jQuery版本,我認為我會提供不同的東西 ,所以這里有一個原生DOM API替代方案:
document.getElementById('previous').setAttribute('control','-6');
是的,我知道你要求jQuery。 永遠不要害怕知道本土的方式。 :O)
讓我看看我是否理解你。 例如,您有代碼:
<a id="previous" href="#"></a>
通過jQuery,你希望它是:
<a id="previous" control="-6" href="#"></a>
這樣對嗎? 如果是。 你只需要這樣做:
$('#previous').attr('control', -6);
如果屬性不存在,則由jQuery創建。 因此,要刪除它,您可以執行以下操作:
$('#previous').removeAttr('control');
你正在做什么不尊重HTML規則和其他一切,但它工作正常,很多插件都做同樣的事情。 ; d
我希望這可能會有所幫助!
再見!
試試這個:
$('#previous').attr('control', '-6');
為什么? $ .attr(); jQuery的功能允許你添加,獲取或更新屬性(class,id,href,link,src,control等等!)。
$("#previous").attr("control", "-6");
HTML:
<a id="previous" href="#">...</a>
jQuery的:
$('#previous').attr('control', '-6');
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.