Jquery selector not working on content loaded thro

2019-06-12 14:13发布

I am having below code to send the value of radio button people have clicked via ajax. But it however only works on the first set of options I give. After the the user press next link and all the options are changed and new one loaeded through ajax. But on that this selector is not working.

$(".options input").click(function(){
var ans = $(this).val();

$.post("sessions", { action: "set_answer", answer: ans, question: qid  },
function(data) {
 alert("Data Loaded: " + data);
});


});

What is the possible solution? Below is how the options are.

<div class="options">
<input id="1"type="radio" name="answer"  value="Two" />Two<br/>
<input id="2"type="radio" name="answer"  value="One"  />One<br/>
<input id="3"type="radio" name="answer"  value="Four"  />Four<br/>
<input id="4"type="radio" name="answer"  value="Five"  />Five<br/>
<input id="5"type="radio" name="answer"  value="Six"  />Six<br/>    
</div>

3条回答
2楼-- · 2019-06-12 14:41

If jQuery 1.7+,try this:

$(document).on('click', '.options', function(){
   if ($(e.target).is('input')) {
      var ans =  $(this).val();

      $.post("sessions", { action: "set_answer", answer: ans, question: qid  }, function(data) {
         alert("Data Loaded: " + data);
      });
   }
});
查看更多
霸刀☆藐视天下
3楼-- · 2019-06-12 14:42

The selector isn't working because the elements that you are trying to access don't exist at the point you are creating them.

To do this you should use Jquery On event handler. This will select elements across the entire document even if you create them pro-grammatically later on as in the case of Ajax.

Usage (untested):

$(".options input").on("click", function(event){
    var ans = $(this).val();

    $.post("sessions", { action: "set_answer", answer: ans, question: qid  },
    function(data) {
     alert("Data Loaded: " + data);
    });

});
查看更多
一夜七次
4楼-- · 2019-06-12 15:01

If latest jQuery,


$('.options input').on('click', function(event) {
....

Or you could try doing:


$(".options input").live("click", function(){
....

Hope it helps

查看更多
登录 后发表回答