2个问题:第一个:我有两种方法可以从数据库中获取数据并将其放入每个下拉菜单中。当我点击第二个菜单时,它会连续发布,所以有很多网络包被发送给数据请求,我的开发人员工具充满了帖子?
第二个问题是,当我从数据库中获取数据时,我该如何执行操作。我正在使用bootstrap下拉菜单。我想要的是当我点击它应删除默认消息并填充所选文本。我已经这样做但它没有选择我从数据库中获取的数据。如果我通过li手动输入数据,那么下拉文本会改变吗?
$(document).ready(function () {
Method();
Method2();
$('.menu1').on('click', 'li', function () {
$('#dropdown_title').html($(this).find('a').html());
});
function Method() {
ajReq = $.ajax({
type: "POST",
url: "Services/Page.asmx/GetService",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (x) {
var opts = '';
$.each(x.d, function (i) {
opts += '<li>' + this.Name + '</li>';
});
$('.menu1').html(opts);
}
});
}
function Method2() {
ajReq = $.ajax({
type: "POST",
url: "Services/Page.asmx/GetService2",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (x) {
var opts = '';
$.each(x.d, function (i) {
opts += '<li>' + this.Name + '</li>';
});
$('.menu2').html(opts);
}
});
}
<div class="drop1" style="display: inline-block;">
<div class="btn-group">
<button type="button" id="Button1" class="btn btn-default dropdown-toggle" data- toggle="dropdown">
<span id="dropdown_title">Name:</span><span class="caret"></span>
</button>
<ul class="dropdown-menu menu1">
<li><a class=""></a></li> //this is where 'a' is which will get populated by data from database
</ul>
</div>
</div>
<div class="drop2" style="display: inline-block;">
<div class="btn-group">
<button type="button" id="Button2" class="btn btn-default dropdown-toggle" data- toggle="dropdown">
<span id="dropdown_title2">Name2:</span><span class="caret"></span>
</button>
<ul class="dropdown-menu menu2">
</ul>
</div>
</div>
答案 0 :(得分:0)
第一个问题: 您可以在POST过程中关闭事件,在SUCCESS之后关闭事件,如下所示,执行表单提交代码
var doPost = function() {
$(this).off('submit', doPost);
var url = '...',
data = {...},
afterPost = function() {
$('#post-form').on('submit', doPost)
};
$.post(url, data, afterPost);
}
$('#post-form').on('submit', doPost);
第二个问题: 如果要将事件与动态数据绑定,可以这样做:
$('.menu1').on('click', 'li', function () {
$('#dropdown_title').html($(this).find('a').html());
});
这种方式可以将事件绑定到绑定事件后创建的DOM
回答更新:
$(document).ready(function () {
Method();
Method2();
$('.menu1').on('click', 'li', function () {
$('#dropdown_title').html($(this).find('a').html());
});
$('.menu2').on('click', 'li', function () {
$('#dropdown_title2').html($(this).find('a').html());
});
});
function Method() {
$.ajax({
type: "POST",
url: "Services/Page.asmx/GetService",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (x) {
var opts = '';
$.each(x.d, function (i) {
opts += '<li>' + this.Name + '</li>';
});
$('.menu1').html(opts);
}
});
}
function Method2() {
$.ajax({
type: "POST",
url: "Services/Page.asmx/GetService2",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (x) {
var opts = '';
$.each(x.d, function (i) {
opts += '<li>' + this.Name + '</li>';
});
$('.menu2').html(opts);
}
});
}