Home >Web Front-end >JS Tutorial >How to add events to dynamically generated select elements using jQuery

How to add events to dynamically generated select elements using jQuery

高洛峰
高洛峰Original
2017-01-03 16:48:061782browse

In the project, the select element needs to be dynamically generated when the button is clicked. To prevent data from being obtained from the server every time the button is clicked (because the data is the same), you can write the code like this

1 , first define the global js variable

var strVoucherGroupSelect ="";

2. Write the code to obtain the server data in js

function genVoucherGroupSelect(rowID){
  return $(strVoucherGroupSelect).attr("id", "sl_" + rowID).parent().html();  //返回增加ID后的下拉框完整html
}
function getVoucherGroupData(){
  $.ajax({
    type: "Post",
    url: "/BillWeb/OrgVoucher/GetVoucherGroup",
    dataType: "json",
    data: "",
    cache: true,
    success: function(res) {
        var str = $("<select></select>");
        var option = "";
        for(var j =0;j < res.length; j++)
        {
          option += "<option value=\"" + res[j].Value + "\">" + res[j].Text + "</option>";
        }
        strVoucherGroupSelect = $(str).html(option).parent().html();
    }
  });
}

3 Write initialization code in the page

$().ready(function(){
    getVoucherGroupData();
  });

4 When you need to dynamically increase the selection, you can write like this

$("#divID").append(genVoucherGroupSelect(rowID) );

5 Add a click event to the select, add

$("#sl_0" + rowID).bind("change", function(){
   alert("你点击了下拉框");
})

after the fourth step

The above article jQuery adds events to the dynamically generated select element The method is all the content shared by the editor. I hope it can give you a reference, and I also hope that everyone will support the PHP Chinese website.

For more jQuery methods of adding events to dynamically generated select elements, please pay attention to the PHP Chinese website!


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn