如何在javascript中使用setAttribute
这是正确的格式吗如何在javascript中使用setAttribute,javascript,Javascript,这是正确的格式吗 var title = new_element.setAttribute('jcarouselindex', "'items+1'"); alert(title); 无需将第二个参数加引号 var title = new_element.setAttribute('jcarouselindex', items+1); 如果要设置自定义属性,则可以使用,例如 var title = new_element.setAttribute('data-jcarouselindex',
var title = new_element.setAttribute('jcarouselindex', "'items+1'");
alert(title);
无需将第二个参数加引号
var title = new_element.setAttribute('jcarouselindex', items+1);
如果要设置自定义属性,则可以使用,例如
var title = new_element.setAttribute('data-jcarouselindex', items+1);
它在语法上是正确的JS/DOM,但HTML中没有“jCarouseIndex”属性,使用
setAttribute
(与设置映射到属性的属性相反)通常是不好的做法,因为它在MSIE中有缺陷(尽管在这种情况下不会导致问题)
不过,您可能不打算将
作为最终结果。使用jQuery
var title=$('new#u element').attr('jcarouselindex','items+1');
警报(标题) 你的引号太多了:
var index = items + 1;
new_element.setAttribute('jcarouselindex', index);
备注:HTML元素中没有定义
jCarouseIndex
属性,因此这不是非常干净的代码。您正在演示如何设置属性,但也可以获取属性。jQuery很好地解决了跨浏览器的兼容性问题,但如果您已经在使用它,那么最好使用.data
。