【问题标题】:error when trying to retrieve class name with jquery尝试使用 jquery 检索类名时出错
【发布时间】:2013-09-13 12:58:52
【问题描述】:

我有以下代码

var allRows = $('.myclass'); ... allRows.each(function() { //现在搜索所有行 var className = this.attr("class"); ... });

我收到一条错误消息

Uncaught TypeError: Object #<HTMLDivElement> has no method 'attr'

我的代码有什么问题?我在 allRows 上做了一个 console.log,它是一个 jquery 对象。

【问题讨论】:

    标签: jquery


    【解决方案1】:

    你应该试试这个,

     var className = $(this).attr("class");// attr is jquery function
     console.log(className);
    

    完整代码

    var allRows = $('.myclass');
    ...
    allRows.each(function() {   //now search through all the rows
        var className = $(this).attr("class");// change this to $(this) here
        console.log(className);            
    });
    

    【讨论】:

    • 当然,谢谢! attr() 是 jquery 方法,所以当然你必须先将它传递给 jquery。
    【解决方案2】:

    改成这样:

    var className = $(this).attr("class");
    

    【讨论】:

      【解决方案3】:

      您应该将this 更改为$(this)

       var className = $(this).attr("class");
      

      【讨论】:

        【解决方案4】:

        你也可以使用className

        var allRows = $('.myclass');
        allRows.each(function () { //now search through all the rows
            var className = this.className;
        });
        

        【讨论】:

          【解决方案5】:

          您没有正确使用“this”。下面给出正确的方法:-

              var allRows = $('.myclass');
                 ...
              $(allRows).each(function() {   //now search through all the rows
                 var className = $(this).attr("class");
                 ...    
              });
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2013-02-25
            • 2021-01-24
            • 2017-04-03
            • 1970-01-01
            • 2011-10-23
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多