简体   繁体   中英

Dynamic parameters in JQuery

I have function in which append method is taking a static parameter.

 function toggle() {
         $("#MS").append($('#hide'));        
    }

What i want is to pass the parameter dynamically from my Hyperlinks click event. In above code that #MS is static which i want to pass dynamically

Code: HTML

<div id="MS">
        <a href="javascript:void(0);" onclick="toggle();">JP MORGAN</a><br>
    </div>

I want to pass the argument from onclick to toggle method and that parameter will be used in the append method.

I have tried several combinations buut it didnt worked. Please help..

My new code after changes

<script>
$(function() { // when the DOM is ready
    var $hide = $('#hide').click(function(){
       $(this).closest('div').hide();
    }); 

    $('a.toggle').click(function(e){
       e.preventDefault();
       $(this).parent().append($hide);
    });
}); 


</script>

<div id="JP">
        <a href="#">JP MORGAN</a><br>       
    </div>

still not working

Since you are using jQuery, you can add classes to your a elements and use parent method:

$(function() { // when the DOM is ready
    var $hide = $('#hide').click(function(){
       $(this).closest('div').hide();
    }); 

    $('a.toggle').click(function(e){
       e.preventDefault();
       $(this).parent().append($hide);
    });
}); 

Retrieve the ID dynamically on the anchor's click event and pass that ID to the function:

$("a").on("click", function(e){
    e.preventDefault();

    $(this).append($('#hide')); 

};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM