无法读取属性'拆分'的未定义

Cannot read property 'split' of undefined

本文关键字:未定义 拆分 读取 属性      更新时间:2023-09-26

当我试图像那样拆分类属性时,我在这里遇到了一个问题

     <div  class='message_holder  user1212 chatid142'></div>

所以从我的功能,我想得到用户id(1212)和聊天id(142)

但我在闲聊中犯了错误我该怎么修。

 function user_chat_id(){
     classList = $(this).attr("class").split(/'s+/); //----here im getting the error
     $.each(classList, function(index, item) {
        if (item.indexOf("user") > -1) {this_id = item;}
        if (item.indexOf("chatid") > -1) {this_chat_id = item;}
     });
   this_id = this_id.replace('user', '');
   this_chat_id = this_chat_id.replace('chatid', '');
   return [this_id,this_chat_id];
   }

编辑:

当我称之为

  $(document).on ("mouseenter", ".message_holder", function () {
    var this_id = user_chat_id();
     alert(this_id);
   })  

为什么您的代码不起作用

$(this)将是当前窗口。其中.attr("class")将是undefined。因此,当您尝试split时,它将抛出一个错误。

显示$(this)的演示将是当前窗口

$(document).ready(function(){
    $("p").click(function(){
        a()
    });
});
function a(){
  console.log($(this))
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Click on this paragraph.</p>

Soluton

将当前元素作为参数传递给函数。

的变更

var this_id = user_chat_id($(this)); //While calling.
function user_chat_id(elem){ // in function definition

您应该使用elem而不是$(this)

演示如何通过元素

$(document).ready(function(){
    $("p").click(function(){
        a($(this))
    });
});
function a(elem){
  console.log(elem)
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Click on this paragraph.</p>

当前代码的问题是,函数中this的值是undefined(如果在严格模式下)或设置为全局上下文(如果不在严格模式中),因为它只是一个常规函数调用。所以,$(this).attr("class")只会返回undefined,然后当你试图对它执行.split()时,你会看到错误。

我建议使用一个更干净的实现,使用正则表达式为您获取数字:

function getId(str, key) {
    var regex = new RegExp("''b" + key + "(''d+)''b");
    var match = str.match(regex);
    return match ? match[1] : null;
}
function user_chat_id(obj){
    var classList = obj.className;
    var userId = getId(classList, "user");
    var chatId = getId(classList, "chatid");
    return [userId, chatId];
}
$(document).on ("mouseenter", ".message_holder", function () {
    var this_id = user_chat_id(this);
    alert(this_id);
});

此外,您显示的HTML:

<div  class='message_holder  user1212 chatid142></div>

class属性上缺少一个右引号。应该是:

<div class='message_holder user1212 chatid142'></div>

工作演示:

function getId(str, key) {
    var regex = new RegExp("''b" + key + "(''d+)''b");
    var match = str.match(regex);
    return match ? match[1] : null;
}
function user_chat_id(obj){
    var classList = obj.className;
    var userId = getId(classList, "user");
    var chatId = getId(classList, "chatid");
    return [userId, chatId];
}
$(document).on ("mouseenter", ".message_holder", function () {
    var this_id = user_chat_id(this);
    alert(this_id);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div  class='message_holder  user1212 chatid142'>Put the mouse over this text</div>