我在使用jQuery定位所选<option>
标记的值时遇到了一些困难。
使用AJAX生成<select>
元素。这是我的以下代码:
<select class="form-control" name="">
<option class="paginate_click active" id="1-page">1</option>
<option class="paginate_click" id="2-page">2</option>
<option class="paginate_click" id="3-page">3</option>
<option class="paginate_click" id="4-page">4</option>
<option class="paginate_click" id="5-page">5</option>
</select>
使用以下jQuery:
j$(document).ready(function() {
j$('#results').on('click', '.paginate_click', function(e) {
j$("#results").prepend('<div class="loading-indication"><img src="/assets/loader.gif" /></div>');
var clicked_id = j$(this).attr("id").split("-");
var page_num = parseInt(clicked_id[0]);
j$("#results").load("development_fetch.php", {'page': (page_num-1)}, function(response, status, xhr){
if ( status == "success" ) {
alert("Do Stuff with results");
}
});
});
});
当我从某个选项中点击时,什么也没发生!请帮忙!
答案 0 :(得分:3)
尝试
j$(function ($) {
//use change event of the select instead of the click event of option
$('#results').on('change', 'select', function (e) {
//use the :selected filter to find the selected option element
var $opt = $(this).find('option:selected');
$("#results").prepend('<div class="loading-indication"><img src="/assets/loader.gif" /></div>');
//use the selected option to find its id
var clicked_id = $opt.attr("id").split("-");
var page_num = parseInt(clicked_id[0]);
$("#results").load("development_fetch.php", {
'page': (page_num - 1)
}, function (response, status, xhr) {
if (status == "success") {
alert("Do Stuff with results");
}
});
});
});
答案 1 :(得分:1)
试试这个。
而不是click
事件绑定change
事件来选择标记而不是选项标记。
此外,您无需编写逻辑来获取pag_num值。它已经存在select
值。
j$(document).ready(function() {
j$('#results').on('change', '.form-control', function(e) {
j$("#results").prepend('<div class="loading-indication"><img src="/assets/loader.gif" /></div>');
// read value of select tag which gives you selected option.
var page_num = j$(this).val();
j$("#results").load("development_fetch.php", {'page': (page_num-1)}, function(response, status, xhr){
if ( status == "success" ) {
alert("Do Stuff with results");
}
});
});
});
工作JSFiddle。
注意:我已经评论了ajax调用并预先添加了图像。
答案 2 :(得分:0)
试试这个
$('#results').on('change', '.form-control', function(e) {
$("#results").prepend('<div class="loading-indication"><img src="/assets/loader.gif" /></div>');
var clicked_id = $(this).attr("id").split("-");
var page_num = parseInt(clicked_id[0]);
$("#results").load("development_fetch.php", {'page': (page_num - 1)}, function(response, status, xhr) {
if (status == "success") {
alert("Do Stuff with results");
}
});
});