Javascript .getAttribute() 有效,但 .attr() 不工作
Javascript .getAttribute() works but .attr() does not
试着理解为什么.getAttribute("id"(可以获取值,而.attr("id"(不能。
我写了一个 Jquery 插件函数,并尝试从使用该插件函数的选择器或 id 中获取选择器或 id。
在我的 HTML 中,插件函数调用是 -
<script>
$(document).ready(function() {
var langObj = {"lang" : "en"};
var curMap = {"testMap" : "tttt"};
$("#test_id").testProduct({
'error_msg' : 'ERROR NOT LOAD.'
}).load(langObj, curMap);
});
</script>
在我的 JQuery 插件函数中 -
(function($){
var pluginName = "testProduct",
defaults = {};
$.test.testProduct = function(element, options) {
this.apiLoadType = {
'ERROR' : 'error'
}
this.options = $.extend({}, defaults, options);
this.element = element;
return this;
};
$.test.testProduct.prototype = {
_load: function(langObj, curMap) {
console.log(this); //Chrome console log #1
console.log(this.element) //Chrome console log #2
this.element.getAttribute("id"); //show the id
this.element.attr("id"); //not show the id
},
//PUBLIC
load: function(langObj, curMap) {
var self = this;
this._load(langObj, curMap);
return this;
}
}
$.fn[pluginName]= function(options) {
var el = null;
this.each(function () {
el = new $.test[pluginName]( this, options );
});
return el;
};
})(jQuery);
铬控制台日志 #1 -
$.testFn.testProduct {apiLoadType: Object, options: Object, element: div#test_id.test_id2, errorElement: null}
apiLoadType: Object
element: div#test_id.test_id2
accessKey: ""
align: ""
baseURI: null
attributes: NamedNodeMap
0: id
...
className:"test_id2"
id:"test_id"
outerHTML: "<div id="test_id" class="test_id2"></div>"
outerText: ""
...
options: Object
__proto__: Object
铬控制台日志 #2 -
<div id="test_id" class="test_id2"></div>
为什么 this.element.getAttribute("id"(; 可以显示元素 id?在这种情况下,我应该使用哪种 Jquery 方法来从我的元素中获取选择器或元素 id?
>this.element
是一个原生的DOM元素,通过JavaScript而不是jQuery访问,所以.attr()
jQuery功能将无法使用它。
尝试。。。
$(this.element).attr("id");
在javascript中你可以这样做
如果您知道元素的 id,则可以执行document.getElementById("id").setAttribute("attribute", "state/value attribute")
如果要删除属性
document.getElementById("id").removeAttribute("attribute");
相关文章:
- jQuery.data('itemname')不工作,但jQuery.attr('data it
- 调用时将.attr添加到不工作的按钮
- Ember数据:DS.attr(“数字”)应该如何工作
- Jquery attr 无法正常工作复选框必需属性
- .attr 选择器不会在每个循环中工作
- Javascript .getAttribute() 有效,但 .attr() 不工作
- jQuery .attr 只能工作一次
- 它是如何工作的?target=$this.attr('data target')|| e.prevent
- jQuery.attr('src')replace在FF中不工作
- multiple attr()在jquery中只能部分工作
- jQuery.attr工作不正常,未检索到链接
- jQuery. attr()不能在jQuery.dialog上工作
- 如何让 jQuery .attr 工作
- 单选按钮被Prop选中,而不与attr一起工作
- jQuery .attr(" disabled ", " disabled ")在IE 10中不工作
- (美元).attr (& # 39; id # 39;);不工作
- 我试图让jquery显示/隐藏和attr显示工作
- 它不工作"onclick"使用attr()从JQuery
- jQuery .attr代码在Drupal中工作
- Jquery attr('src')在ie8中未定义(在FF中工作)