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

时间:2013-09-25 09:18:09

标签: javascript jquery html-select

这段代码适用于所有现有的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);
        })
    }
  });
});

2 个答案:

答案 0 :(得分:1)

$(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();

});

答案 1 :(得分:0)

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

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

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