我的结构如下:
<div class="panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title">Tiger128 (v2)</h3>
</div>
<div class="panel-body">
<input class="form-control" id="tiger128v2" placeholder="String to Hash" type="text">
</div>
<div class="panel-footer">
<a class="btn btn-primary generate-hash" data-hash="tiger128v2">Generate Hash</a>
</div>
</div>
当用户按下 <a>
它运行一个 jQuery 函数(使用 $('.generate-hash')
选择器),它生成一个 $.getJSON
。请求传递 data-hashtype
.当它返回 JSON 对象时,我需要它将一些文本附加到 <div class="panel-body">
但是正如您所看到的,他们都没有 ID。
我尝试过的是:
$(this).parent().prev('.panel-body').append('Appending some text');
$(this).parent().parent().siblings(".panel-body").append('test');
但我无法让它工作。有什么建议吗?
$('.generate-hash').click(function (e) {
e.preventDefault();
var hashtype = $(this).data('hash');
var string = $(this).closest('.panel').find('input').val();
console.log('Started hash request for ' + hashtype + ' with a value of ' + string);
$.getJSON('ajax/hash.php', {
hashtype: hashtype,
string: string
})
.success(function(data) {
console.log('success function');
if(data.type == 'success'){
// Here is where i need to select the parents
$(this).parent().parent().siblings(".panel-body").append('test');
$(this).parent().prev('.body').append('<div class="alert alert-info"><strong>Generated Hash:</strong> <code>' + data.hash + '</code></div>');
console.log('success msg found');
}else{
$(this).parent().prev('.body').append('<div class="alert alert-' + data.type + '">' + data.msg + '</div>');
console.log('error msg found');
}
})
.fail(function() {
$(this).parent().prev('.body').append('<div class="alert alert-error"><strong>Error:</strong> We could not generate the hash for some reason. The details are below:</div>');
console.log('unable to find hash.php or other error');
});
});
最佳答案
你可以使用.prev()
方法:
$(this).parent().prev('.body').append('Something');
或者.closest()
方法:
$(this).closest('.box').find('.body').append('Something');
编辑:
你应该缓存 this
对象,在 Deferred 对象的处理程序的上下文中 this
不引用被点击的元素,也替换 .success( )
与 .done()
:
$('.generate-hash').click(function (e) {
// ...
var $this = $(this);
$.getJSON('ajax/hash.php', {
hashtype: hashtype,
string: string
})
.done(function(data) {
console.log('success function');
if(data.type == 'success'){
// Here is where i need to select the parents
$this.parent().parent().siblings(".panel-body").append('test');
// ...
})
.fail(function() {
$this.parent()...
});
});
关于javascript - 从没有 ID 的其他女儿访问女儿 DIV,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19239215/