jquery click不适用于具有数据属性的元素

问题描述 投票:-1回答:1

我试图在li元素上触发click事件,但它不起作用。

以下是我的代码

<html>
    <head>
            <script
            src="https://code.jquery.com/jquery-3.3.1.min.js"
            integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
            crossorigin="anonymous"></script>
    </head>
    <body>
      <ul>
        <li class="select userlist" data-userid="172" data-type="employer" data-jobid="218">
            <div class="cl-left">
              <div class="image"> <img src="userimages/75541c25341c9d7f88012c77f91b495578c46925.jpg" class="userimage"><span class="onlinestatus on"></span> </div>
            </div>

          </li>
       </ul>
    </body>
    <script>
    $(function(){
        var not_yet_assigned = 172;
        $('.userlist[data-userid="'+not_yet_assigned+'"][data-jobid="218"]')[0].click();
        $('.userlist[data-userid="'+not_yet_assigned+'"][data-jobid="218"]').click();
        $('.userlist[data-userid="'+not_yet_assigned+'"][data-jobid="218"]').trigger('click');
        $('.userlist[data-userid="'+not_yet_assigned+'"][data-jobid="218"]').on('click', function(){
            alert('clicked');
        });
    });
    </script>
</html>
javascript jquery
1个回答
4
投票

根据我的理解,你想通过jQuery触发click事件,为此你需要在触发它之前定义click函数,就像这样

<html>
    <head>
            <script
            src="https://code.jquery.com/jquery-3.3.1.min.js"
            integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
            crossorigin="anonymous"></script>
    </head>
    <body>
        <li class="select userlist" data-userid="172" data-type="employer" data-jobid="218">
            <div class="cl-left">
              <div class="image"> <img src="userimages/75541c25341c9d7f88012c77f91b495578c46925.jpg" class="userimage"><span class="onlinestatus on"></span> </div>
            </div>

          </li>
    </body>
    <script>
    $(function(){
        var not_yet_assigned = 172;
         $('.userlist[data-userid="'+not_yet_assigned+'"][data-jobid="218"]').on('click', function(){
            alert('clicked');
        });
        $('.userlist[data-userid="'+not_yet_assigned+'"][data-jobid="218"]')[0].click();
        $('.userlist[data-userid="'+not_yet_assigned+'"][data-jobid="218"]').click();
        $('.userlist[data-userid="'+not_yet_assigned+'"][data-jobid="218"]').trigger('click');
       
    });
    </script>
</html>
© www.soinside.com 2019 - 2024. All rights reserved.