Jquery selector not working on content loaded through ajax

偶尔善良 提交于 2019-12-12 10:18:01

问题


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>

回答1:


If latest jQuery,


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

Or you could try doing:


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

Hope it helps




回答2:


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:


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);
    });

});


来源:https://stackoverflow.com/questions/9426149/jquery-selector-not-working-on-content-loaded-through-ajax

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!