Jquery selector not working when adding html dynamically

I can dynamically add the "select" element to the DOM, after adding it to the DOM, I want to change the html content of the last "select" (the last "select" was added dynamically), but it failed ...

(I cannot set the parameter value in param_html, because I have to set them using an ajax request later.)

<script>
    $(function(){
      var param_html = '<select class="params"></select>';
      $("input[value='+']").click(function(){
        $('#parameters').append(param_html);
          $('.params :last').html('<option>aaa</option><option>keyword in profile</option><option>last tweet</option>');
      });

    });
  </script>
  <div id="parameters">
    <input type="button" value="+">
    <select class="params"><option>1</option><option>2</option></select>
  </div>

any suggestion appreciated.

+3
source share
3 answers

print the space between the parameters and: last

$('.params:last').html('<option>aaa</option><option>keyword in profile</option><option>last tweet</option>');
+6
source

your content seems to be added after loading dom.

try living http://api.jquery.com/live/

+1
source

, CSS- $('.params:last-child') $('.params:last') , .

, :

$(function(){
      var param_html = '<select class="params"></select>';
      $("input[value='+']").click(function(){
        $('#parameters').append(param_html);
          $(param_html).html('<option>aaa</option><option>keyword in profile</option><option>last tweet</option>');
      });

    });

If you intend to use AJAX in the future, then the same idea will work instead of re-choosing to use the object in what you created.

0
source

All Articles