2017-03-12 250 views
-1

是否可以更改元素的属性type?把我的头脑讨论一下 - 我能找到的就是如何更改属性的value更改属性类型

我想在上面的元素上更改hrefsrc。我有一个脚本,将元素类型更改为移动设备的iframe,并且我需要该属性为src类型才能工作。

<a class="colorbox cboxElement" href="http://example.com">Diablo</a> 

这可能吗?

+3

SRC不会在锚要动态地更改ID – zer00ne

+0

做工作? – Monicka

+1

为什么你需要向锚元素添加一个无效属性,你认为这个问题解决了什么问题? –

回答

4

使用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 
}) 
+0

这对我很好! – user3344734

+0

请注意,jQuery和普通的JS解决方案并不等价,因为jQuery版本能够更改多个元素的属性(因为它在幕后循环)。 – nnnnnn

0

是的,您可以更改任何属性。

用途:

element.setAttribute(attribute_name, attribute_value) 

,并获得属性的值使用

element.getAttribute(attribute_name) 

请注意,并非所有的属性都将有元素的影响。 例如,设置类型属性输入元素将创建给定类型的输入,但将其设置为范围什么都不做。

如果你想持有属性的一些数据信息,我会建议使用dataset API

0

如果你想使用的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>