首页 > 解决方案 > 传递参数的最佳方式(非常简单的 jquery/html)

问题描述

我使用用户名创建多个按钮

<a id="message-' + onlineUsers[i].username + '"></a>

然后我会用 id 拆分-来获取用户名?

$('a[id^="message-"]').click(function () {
    //I need to get the username here
});

不知何故,这对我来说看起来不正确。正确的做法是什么?

标签: jqueryhtml

解决方案


你可以像这样使用它:

<!DOCTYPE html>
<html>
<head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <title>Hello, world!</title>
  <style>
  </style>
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script>
<script>
  $(function(){
      $('a[id^="message-"]').click(function () {
            //I need to get the username here
            var thisElem = jQuery(this);
            var lastItem = thisElem.attr("id").split("-").pop(-1);

            console.log(lastItem); //result "myusername"
        });
   });
</script>
</head>
<body>
       <a id="message-myusername">Click Me</a>
</body>
</html> 

推荐阅读