使 jQuery 代码适用于动态添加的内容

make jquery code work for dynamically added content

本文关键字:添加 动态 jQuery 代码 适用于      更新时间:2023-09-26

这段代码适用于所有现有的 html 下拉列表,但如何使其也适用于动态添加的下拉列表

这是jquery代码

$(document).ready(function () {
  $('select.select').each(function () {
    var title = $(this).attr('title');
    if ($('option:selected', this).val() != '') {
      title = $('option:selected', this).text();
      $(this)
        .css({
          'z-index': 10,
          'opacity': 0,
          '-khtml-appearance': 'none'
        })
        .after('<span class="select">' + title + '</span>')
        .change(function () {
          val = $('option:selected', this).text();
          $(this).next().text(val);
        })
    }
  });
});
$(document).ready(function () {
    initDropDowns();
    function initDropDowns(){
      $('select.select').each(function () {
        var title = $(this).attr('title');
        if ($('option:selected', this).val() != '') {
          title = $('option:selected', this).text();
          $(this)
            .css({
              'z-index': 10,
              'opacity': 0,
              '-khtml-appearance': 'none'
            })
            .after('<span class="select">' + title + '</span>')
            .change(function () {
              val = $('option:selected', this).text();
              $(this).next().text(val);
            })
        }
      });
    }
    // on dropDowns add --> initDropDowns();
});

而不是 $(document).ready() 你需要使用 $(document).live()

.ready() 允许您注册一个在 DOM 准备就绪时触发的回调 - 这类似于使用 window.onload,但更早触发(您可以注册多个回调)。

.live() 允许您基于选择器注册对一系列事件的回调,选择器持续监控 DOM 并将自身注册到添加的新节点。