如何根据单击的按钮发送id参数?

时间:2016-05-14 22:39:56

标签: javascript jquery html

演示和完整代码如下:https://jsfiddle.net/oscar11/o5qn5gum/8/

我的HTML代码是这样的:

<button type="button">Click Me</button>

<div id="tes">

</div>


<!-- Modal Currency-->
<div class="modal fade" id="priceModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">


            </div>
            <div class="modal-body">

            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
            </div>
        </div>
        <!-- /.modal-content -->
    </div>
    <!-- /.modal-dialog -->
</div>

我的Javascript代码是这样的:

$(document).ready(function(){
        $("button").click(function(){

            $.ajax({
                //type: 'POST',
                //url: 'script.php',
                success: function(data) {
                    var isitable = '';
                    isitable += '<br><button class="btn btn-primary tes" id="NationCd=ID&CityCd=JKT">Book 1</button><br><br>';
                    isitable += '<button class="btn btn-primary test" id="NationCd=ID&CityCd=BAI">Book 2</button><br><br>';
                    isitable += '<button class="btn btn-primary test" id="NationCd=ID&CityCd=JOG">Book 3</button><br>';

                    // console.log(isitable);
                    $("#tes").html(isitable);                   
                }
            });
        });

        $(".test").click(function(){
            console.log('tes');
            var id = this.id;
            console.log(id);
        });
    });

点击“点击我”按钮,会显示三个按钮。看看jsfidde。

单击按钮时(例如,单击“book 1”按钮),将发送参数ID。我在console.log(this.id); $(".test").click(function(){ {{1}},但它不起作用。

解决我问题的任何解决方案?

谢谢

1 个答案:

答案 0 :(得分:1)

由于您进行了AJAX调用,您必须将点击事件放在success部分中,如下所示:

$(document).ready(function(){
  $("button").click(function(){

    $.ajax({
      //type: 'POST',
      //url: 'script.php',
      success: function(data) {
        var isitable = '';
        isitable += '<br><button class="btn btn-primary test" id="NationCd=ID&CityCd=JKT">Book 1</button><br><br>';
        isitable += '<button class="btn btn-primary test" id="NationCd=ID&CityCd=BAI">Book 2</button><br><br>';
        isitable += '<button class="btn btn-primary test" id="NationCd=ID&CityCd=JOG">Book 3</button><br>';

        // console.log(isitable);
        $("#tes").html(isitable);
        $(".test").click(function(){
          console.log('tes');
          var id = this.id;
          console.log(id);
        });

      }
    });
  });


});

Fiddle