目前,我有一个脚本,以编程方式使用jQuery在页面上创建多个面板(是的,Twitter面板)。它们基本上是一样的,只是每个文本里面都有一些动态文本,在文本下面有一个按钮。就像这样:
<div class="panel panel-default" id="panel1">
<div class="panel-body">There's some dynamically-generated text here.</div>
<div class="panel-footer">
<button class="btn btn-default btn-block">Click Here</button>
</div>
</div>因此,我试图为按钮编写一个onclick方法,它将抓住面板的上方,然后替换其中的文本。替换文本函数没有问题,但我花了很长时间编写适当的jQuery来获取正确的元素。
我试过什么
首先,我尝试使用“这个”作为上下文,但是,正如预期的那样,这是行不通的。
$(".panel-body", this).text(updateContent())我知道这会奏效的:
$("#panel1 .panel-body").text(updateContent())因此,我尝试在我构建ids的同一个循环中动态构建这个选择器,但是使用所有单引号、双引号和符号,我无法让javascript正确地解析行。
我相信解决办法很简单,但我的眼睛交叉了,我看不清楚。
发布于 2015-01-23 04:15:09
假设this是您的按钮元素,然后尝试
$(this).closest('.panel').find('.panel-body').text("foobar")使用closest()的优点是您可以任意深度嵌套按钮,而无需更改处理程序。
$(function(){
$('.panel .btn').click(function(){
$(this).closest('.panel').find('.panel-body').text('foobar');
})
});<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="panel panel-default" id="panel1">
<div class="panel-body">There's some dynamically-generated text here.</div>
<div class="panel-footer">
<button class="btn btn-default btn-block">Click Here</button>
</div>
</div>
<div class="panel panel-default" id="panel1">
<div class="panel-body">There's some dynamically-generated text here.</div>
<div class="panel-footer">
<button class="btn btn-default btn-block">Click Here</button>
</div>
</div>
<div class="panel panel-default" id="panel1">
<div class="panel-body">There's some dynamically-generated text here.</div>
<div class="panel-footer">
<button class="btn btn-default btn-block">Click Here</button>
</div>
</div>
发布于 2015-01-23 04:17:58
尝尝这个。
$(this).parent().prev().html("updated content");发布于 2015-01-23 04:19:04
您非常接近,而不是直接使用this,您需要首先使用closest找到父面板
$(".panel-body", $(this).closest('div.panel')).text(updateContent())https://stackoverflow.com/questions/28102909
复制相似问题