是否可以更改元素的属性type
?把我的头脑讨论一下 - 我能找到的就是如何更改属性的value
。更改属性类型
我想在上面的元素上更改href
到src
。我有一个脚本,将元素类型更改为移动设备的iframe,并且我需要该属性为src类型才能工作。
<a class="colorbox cboxElement" href="http://example.com">Diablo</a>
这可能吗?
是否可以更改元素的属性type
?把我的头脑讨论一下 - 我能找到的就是如何更改属性的value
。更改属性类型
我想在上面的元素上更改href
到src
。我有一个脚本,将元素类型更改为移动设备的iframe,并且我需要该属性为src类型才能工作。
<a class="colorbox cboxElement" href="http://example.com">Diablo</a>
这可能吗?
使用removeAttr()
方法来删除属性和attr()
方法来设置的属性。
$('.colorbox').attr('src', function() {
return $(this).attr('href');
}).removeAttr('href');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a class="colorbox cboxElement" href="http://example.com">Diablo</a>
使用纯JavaScript使用Element#setAttribute
方法设置属性,你可以得到使用Element#getAttribute
方法属性值,并使用Element#removeAttribute
方法删除属性。
var ele = document.querySelector('.colorbox');
ele.setAttribute('src', ele.getAttribute('href'));
ele.removeAttribute('href');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a class="colorbox cboxElement" href="http://example.com">Diablo</a>
FYI: jQuery的方法将多个元素的工作,在Javascript中你需要遍历元素集合更新多个。
对于如:
// for older browser use [].slice.call(....).forEach
Array.from(document.querySelectorAll('.colorbox')).forEach(function(ele){
// do the rest here
})
这对我很好! – user3344734
请注意,jQuery和普通的JS解决方案并不等价,因为jQuery版本能够更改多个元素的属性(因为它在幕后循环)。 – nnnnnn
是的,您可以更改任何属性。
用途:
element.setAttribute(attribute_name, attribute_value)
,并获得属性的值使用
element.getAttribute(attribute_name)
请注意,并非所有的属性都将有元素的影响。 例如,设置类型属性输入元素将创建给定类型的输入,但将其设置为范围什么都不做。
如果你想持有属性的一些数据信息,我会建议使用dataset API
如果你想使用的JavaScript只是,你可以得到使用getAttribute
属性,设置使用setAttribute
新的属性,并使用removeAttribute
删除旧的属性。
var tag = document.getElementsByClassName('cboxElement')[0];
tag.setAttribute('src', tag.getAttribute('href'));
tag.removeAttribute('href');
<a class="colorbox cboxElement" href="http://example.com">Diablo</a>
SRC不会在锚要动态地更改ID – zer00ne
做工作? – Monicka
为什么你需要向锚元素添加一个无效属性,你认为这个问题解决了什么问题? –