我有下面的代码工作:无法获得最接近工作
$(document).ready(function() {
var xhr = false;
func_two();
$('.button_one').click(function(event) {
event.preventDefault();
if ($("#textbox_one").val().length > 0) {
func_one($("#textbox_one").val());
} else {
func_two();
}
});
function func_one(phrase) {
xhr = $.ajax({
type: 'POST',
url: 'url here',
data: '{phrase: "' + phrase + '"}',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function(data) {
$("#inner_div").empty();
if(data.d[0]) {
$.each(data.d, function(index, row) {
$("#inner_div").append("dynamic data goes here");
});
}
}
});
}
function func_two() {
$('#inner_div').empty().append("static data goes here");
}
});
这工作得很好,因为我直接指定其标签造成影响和标记获取的影响。问题在于这些div实际上是小部件或小工具,我需要允许用户在任何给定时间在屏幕上拥有超过1个这些小部件或小工具。当我尝试这样做时,事情似乎完全错误,因为“我假设”使用控件和div的id。
所以,我一直在使用类代替,这似乎在测试代码,在这里工作的尝试:
$(this).closest('.main_div').find('.sub-div').text("data goes here");
然而,当我尝试使用这个代码上面的原代码,它似乎并没有工作。根据Chromium的开发工具,它给了我一个Cannot call method 'closest' of undefined
。
,我已经试过这似乎不工作的代码如下所示:
$(document).ready(function() {
var xhr = false;
func_two();
$('.button_one').click(function(event) {
event.preventDefault();
if ($("#textbox_one").val().length > 0) {
func_one($(this), $("#textbox_one").val());
} else {
func_two($(this));
}
});
function func_one(that, phrase) {
xhr = $.ajax({
type: 'POST',
url: 'url here',
data: '{phrase: "' + phrase + '"}',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function(data) {
$("#inner_div").empty();
that.closest('.outer_div').find('.inner_div').empty();
if(data.d[0]) {
$.each(data.d, function(index, row) {
that.closest('.outer_div').find('.inner_div').append(row.column);
});
}
}
});
}
function func_two(that) {
that.closest('.outer_div').find('.inner_div').append("static data goes here");
}
});
的HTML看起来像这样
<div class="outer_div">
<div class="inner_div">
results go here
</div>
<div class="footer_div">
<input type="button" class="button_one" />
</div>
</div>
有人可以帮我实现了测试代码到原始代码?
是您的按钮元素,主要的div里面有什么背景? – Bryan
如果'that'是'undefined',那么你不会传递任何东西给'func_one'。 –
@Bryan Moyles,是的按钮元素和subdiv在main_div内。 – oshirowanen