javascript - 我可以在 javascript 中使用 ".attr()"函数吗?

标签 javascript

“.getAttribute”用于java脚本注入(inject)编码。
在 java 脚本函数中使用“.attr()”。
那么我可以在java脚本注入(inject)编码中使用“.attr”值吗?

最佳答案

号码attr()是 jQuery(和其他一些 Javascript 库)的函数。它不是 Javascript 的原生函数。
在 jQuery 中, attr() 应该在 jQuery 对象或集合上调用。不能针对 DOM 元素调用它。正如您正确识别的那样,如果您不想使用库,则需要使用 getAttribute() .
以下示例展示了如何使用 jQuery 和 Javascript 获取相同的信息:
Javascript:

var src = document.getElementById('myImg').getAttribute('src');
jQuery:
var src = $('#myImg').attr('src');
还值得注意的是 attr() 之间的 jQuery 差异。和 prop() , 例如:

attr( attribute )
Get the value of an attribute for the first element in the set of matched elements or set one or more attributes for every matched element.

prop( propertyName )
Get the value of a property for the first element in the set of matched elements or set one or more properties for every matched element.


您可以在此处阅读更多关于差异的信息 > .prop() vs .attr()

关于javascript - 我可以在 javascript 中使用 ".attr()"函数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31746841/

相关文章:

javascript - 通过 JavaScript 查明某个元素是否被遮挡

javascript - ScrollView 切断平铺列表的底部

javascript - promise 不等待完成

javascript - 没有选中属性的复选框

javascript - 客户端与服务器端数据操作

javascript - 如何使用单击按钮更改状态值

php - 如何将ajax排序结果放入html div中

javascript - 如何在使用 PHP 插入数据库之前检查任何输入值是否有数据?

javascript - 简明箭头函数体语法

javascript - 灾难性回溯错误验证字符串