私は動作する次のコードを持っています:
$(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 が事実上のウィジェットまたはガジェットであり、ユーザーがいつでも画面上にこれらのウィジェットまたはガジェットを複数表示できるようにする必要があることです。コントロールとdivにIDを使用することを「想定」しているため、これを試してみると完全にうまくいかないようです。
そのため、代わりにクラスを使用してみました。これは、ここのテスト コードで機能するようです。
$(this).closest('.main_div').find('.sub-div').text("data goes here");
ただし、このコードを上記の元のコードに適用しようとすると、うまくいかないようです。Cannot call method 'closest' of undefined
Chromiumの開発者ツールに従って私に与えます。
私が試したコードは次のようになります。
$(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>
テストコードを元のコードに実装するのを手伝ってもらえますか?