问题
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