Javascript .getAttribute() 有效,但 .attr() 不工作

Javascript .getAttribute() works but .attr() does not

本文关键字:attr 工作 有效 getAttribute Javascript      更新时间:2023-09-26

试着理解为什么.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");