how to call jQuery(this) from anchor tag onclick function

后端 未结 5 1806
礼貌的吻别
礼貌的吻别 2020-12-17 23:31

I have

 
  • New Test
  • &
相关标签:
5条回答
  • 2020-12-17 23:40

    You need to send the element through the function like this

    HTML

    onclick="setSelectedTestPlan(this);"
    

    js

    function setSelectedTestPlan(ele) {      
           jQuery("#tree ul li").each(function () {
                jQuery(this).removeClass("selected");
            });
    
            jQuery(ele).closest('li').addClass("selected");
        }
    
    0 讨论(0)
  • 2020-12-17 23:55

    One line:

    jQuery(this).closest('li').addClass("selected").siblings().removeClass("selected");
    

    but you will have to amend your event to pass through 'this';

    onclick="setSelectedTestPlan(this);"
    
    0 讨论(0)
  • 2020-12-18 00:01

    HTML

    <li><a onclick="setSelectedTestPlan(this);" href="javascript:void(0);">New Test</a></li>
    

    js

    function setSelectedTestPlan(el) {      
           jQuery("#tree ul li").removeClass("selected");
           jQuery(el).closest('li').addClass("selected");
        }
    

    or

    js

    function setSelectedTestPlan(el) { 
       jQuery(el).closest('li').addClass("selected").siblings().removeClass("selected");
    }
    
    0 讨论(0)
  • 2020-12-18 00:01

    HTML

    <li><a onclick="setSelectedTestPlan.call(this, event);" href="javascript:void(0);">New Test</a></li>
    

    JS

    function setSelectedTestPlan(e) {
       jQuery(this)closest('li').addClass("selected").siblings().removeClass("selected");
    }
    
    0 讨论(0)
  • 2020-12-18 00:04
    function setSelectedTestPlan(e) {
        jQuery("#tree ul li").each(function () {
            jQuery(this).removeClass("selected");
        });
    
        jQuery(e).closest('li').addClass("selected");
    }
    
     <li><a onclick="setSelectedTestPlan(this);" href="javascript:void(0);">New Test</a></li>
    

    alternative

        <ul>
            <li><a class="mylink" href="javascript:void(0);">New Test</a></li>
            <li><a class="mylink" href="javascript:void(0);">New Test fdgfdgfdgfdgfdgfdgfdgfdg fdg</a></li>
            <li><a class="mylink" href="javascript:void(0);">New Plan</a></li>
            <li><a class="mylink" href="javascript:void(0);">Test</a></li>
        </ul
    
    
    $(function(){
    $(".mylink").click(function(e){
         $(".mylink").parents("li").removeClass("selected");
         $(this).parents("li").addClass("selected");
         e.preventDefault();   
       });
     });
    
    0 讨论(0)
提交回复
热议问题