开发者

How to use setAttribute in javascript

Is开发者_运维问答 this the correct format?

var title = new_element.setAttribute('jcarouselindex', "'items+1'");
alert(title);


No need to put the second parameter in quotes.

var title = new_element.setAttribute('jcarouselindex', items+1);

If you want to set a custom attribute then you can use HTML5 data-attributes, something like

var title = new_element.setAttribute('data-jcarouselindex', items+1);


It is syntactically correct JS/DOM, but there is no 'jcarouselindex' attribute in HTML and using setAttribute (as opposed to setting properties that map to attributes) is generally bad practice as it is buggy in MSIE (although not in such a way that will cause a problem in this case).

You might not be intending to have <foo jcarouselindex="&#39;items+1&#39;"> as your end result though.


Using jQuery?

var title = $('#new_element').attr('jcarouselindex', "'items+1'"); alert(title);


You have too many quotes:

var index = items + 1;
new_element.setAttribute('jcarouselindex', index);

Remark: there's no jcarouselindex attribute defined in HTML elements so this is not very clean code.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜