Vic*_*scu 14 html javascript jquery
好吧,我有这个jQuery图像幻灯片,它使用<a>中的属性"control".看到它没有验证我搜索了一种通过jQuery在我的HMTL中添加这个属性的方法,但我没有找到任何相关的东西.现在我并不关心我的页面有多有效,但我真的很好奇如何在HTML标记内添加HTML属性.
如果我对我的解释不够清楚,我有这个代码:
<a id="previous" control="-6" href="#"></a>
Run Code Online (Sandbox Code Playgroud)
我想用jQuery 添加control =" - 6".
Bru*_*oLM 27
使用jQuery的attr功能
$("#previous").attr("control", "-6");
Run Code Online (Sandbox Code Playgroud)
一个例子
// 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");
Run Code Online (Sandbox Code Playgroud)
在jsFiddle上查看此示例
您也可以使用data函数在元素上存储值.以相同的方式工作,例如:
$("#previous").data("control"); // undefined
$("#previous").data("control", "-6"); // set the element data
$("#previous").data("control"); // retrieve -6
Run Code Online (Sandbox Code Playgroud)
使用data您可以存储更复杂的值,如对象
$("#previos").data("control", { value: -6 });
($("#previos").data("control")).value; // -6
Run Code Online (Sandbox Code Playgroud)
use*_*716 14
由于这里已经很好地介绍了jQuery版本,我认为我会提供不同的东西,所以这里有一个原生DOM API替代方案:
document.getElementById('previous').setAttribute('control','-6');
Run Code Online (Sandbox Code Playgroud)
是的,我知道你要求jQuery.永远不要害怕知道本土的方式.:O)