传递参数的最佳方式(非常简单的jquery / html)

时间:2018-05-02 15:57:30

标签: jquery html

我使用用户名

创建了多个按钮
<a id="message-' + onlineUsers[i].username + '"></a>

然后我会通过-拆分ID以获取用户名?

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

不知怎的,这对我来说不合适。这样做的正确方法是什么?

3 个答案:

答案 0 :(得分:0)

你可以像这样使用它:

<!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> 

答案 1 :(得分:0)

为每个A标签提供相同的类和名称标签中的变量用户名,如此

<a class="yourClassName" name="' + onlineUsers[i].username+'"></a>

现在更改您的点击功能

$('.yourClassName').click(function () {
     alert( $(this).attr('name') );
}

答案 2 :(得分:0)

您可以使用数据。这是最普通的方式。并使用class来获取click事件。

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

并获取数据:

$(".message").click(function() {
    var username = $(this).data("username");
});

https://api.jquery.com/data/