给定一个 HTML 元素,我想使用 Javascript 获取其 src 属性的原始值。
如果 src 值为相对路径,则 element.src 返回绝对路径。
例如:
//ssss.com ==> http(s)://ssss.com
blabla ==> http(s)://ssss.com/path/blabla
我知道可以将 HTML 代码作为字符串获取并对其进行过滤,但这效率不高。
我正在寻找有效且干净的方法来提取 src/href 属性的原始值,给定带有属性的 HTML 元素。
谢谢!
最佳答案
您将对象属性与属性值混淆了。只使用 getAttribute()
有什么问题吗? ?
var element = document.getElementById('test');
console.log( element.href );
console.log( element.getAttribute('href') );
<a href="test.html" id="test">Testy</a>
请注意element.href
由浏览器解析,而 getAttribute()
返回 DOM 中指定的原始字符串。您也可以类似地使用 getAttribute('src')
对于 <img />
元素。
为了完整起见,这与 jQuery 中演示的行为相同。大多数开发人员会同义词地使用它们,但它们实际上有细微的不同。
例如:
console.log( $('#test').prop('href') );
console.log( $('#test').attr('href') );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="test.html" id="test">Testy</a>
注意如何 prop()
行为方式与 element.href
相同,和attr()
与 getAttribute()
相同.
关于javascript - 在javascript中获取href和src属性的原始值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51896620/