Home > Web Front-end > JS Tutorial > body text

How to add events to dynamically generated select elements using jQuery

高洛峰
Release: 2017-01-03 16:48:06
Original
1681 people have browsed it

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();
    }
  });
}
Copy after login

3 Write initialization code in the page

$().ready(function(){
    getVoucherGroupData();
  });
Copy after login

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

$("#divID").append(genVoucherGroupSelect(rowID) );
Copy after login

5 Add a click event to the select, add

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

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!


Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!