更改事件对动态生成的元素不起作用 - Jquery

Uth*_*imi 5 javascript ajax jquery

我使用jquery Ajax动态生成dropdownList,生成的dropdown的id为specificationAttribute.我想为新标签生成添加事件生成(specificationAttribute),为此我在下面创建scriptwindow.load:

$(document).on('change', '#specificationattribute', function () {
    alert("Clicked Me !");
});
Run Code Online (Sandbox Code Playgroud)

但它不起作用.我尝试更多的方式click,live但我不能得到任何结果.

的jsfiddle

来自小提琴的代码:

$(window).load(function () {
  $("#specificationCategory").change(function () {
        var selected = $(this).find(":selected");
        if (selected.val().trim().length == 0) {
            ShowMessage('please selecet ...', 'information');
        }
        else {

            var categoryId = selected.val();
            var url = $('#url').data('loadspecificationattributes');

            $.ajax({
                url: url,
                data: { categoryId: categoryId, controlId: 'specificationattribute' },
                type: 'POST',
                success: function (data) {
                    $('#specificationattributes').html(data);
                },
                error: function (response) {
                    alert(response.error);

                }
            });

        }

    });



    $(document).on('change', '#specificationAttribute', function () {
        alert("changed ");

    });
    }
Run Code Online (Sandbox Code Playgroud)

Mar*_*iss 4

你的小提琴有语法错误。由于下拉列表会生成一个选择,因此我们使用一个。

对于我的回答,我使用了这个 HTML,稍后会详细介绍:您的代码中的内容不匹配

<select id="specificationAttribute" name="specificationAttribute">
</select>
Run Code Online (Sandbox Code Playgroud)

更新代码:(参见内联注释,一些是建议,一些是错误)

$(window).on('load', function() {
  $("#specificationCategory").on('change',function() {
    var selected = $(this).find(":selected");
    // if there is a selection, this should have a length so use that
    // old:  if (selected.val().trim().length == 0) {
    if (!selected.length) { // new
    // NO clue what this is and not on the fiddle so commented it out
    //  ShowMessage('please selecet ...', 'information');
      alert("select something a category");// lots of ways to do this
    } else {
      var categoryId = selected.val();
      var url = $('#url').data('loadspecificationattributes');
      $.ajax({
        url: url,
        data: {
          categoryId: categoryId,
          controlId: 'specificationattribute'
        },
        type: 'POST',
        success: function(data) {
           // THIS line id does not match my choice of specificationAttribute so I changed it
          $('#specificationAttribute').html(data);
        },
        error: function(response) {
          alert(response.error);
        }
      });
    }
  });

  // THIS should work with the markup I put as an example
  $(document).on('change', '#specificationAttribute', function() {
    alert("changed ");
  });
});// THIS line was missing parts
Run Code Online (Sandbox Code Playgroud)