简体   繁体   中英

jQuery - Pass variable to click function

I have a simple jQuery question with the following code:

 <script>
    $(document).ready(function() {
    $("#changeText").click(function() {
        $.get("test.php", { sectid: "1"},
            function(data){
            $("#textBox").html(data);
        });
    });
    });
 </script>

My HTML is as follows:

<a id="changeText" href="#">Change</a>
<div id="textBox">This text will be changed to something else</div>

I'd like to pass a variable into the .click function in place of "1" but can't seem to get the syntax correct. Can someone point me the right direction?

Thanks.

You just use the variable name, for example:

$(document).ready(function() {
  $("#changeText").click(function() {
    var myVariable = "1";
    $.get("test.php", { sectid: myVariable },
        function(data){
        $("#textBox").html(data);
    });
  });
});

Or if it's a value from something for example:

$.get("test.php", { sectid: $(this).attr("something") },

You can set the variable before the function is called. Then read it's value after.

Example (using jQuery's .data ):

$("#changeText").data('sectid', '1');

 $("#changeText").click(function() {
    $.get("test.php", {sectid: $(this).data('sectid')},
        function(data){
          $("#textBox").html(data);
    });
});

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