[英]How can I make a button change text in a nearby element?
目前,我有一个脚本,可以使用jQuery在页面上以编程方式创建多个面板(是的,Twitter Bootstrap面板)。 它们基本上是相同的,除了每个内部都有一些动态文本,并且在文本下方有一个按钮。 有点像这样:
<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来抓取正确的元素时遇到了麻烦。
我尝试过的
首先,我尝试使用“ this”作为上下文,但是,正如预期的那样,这没有用。
$(".panel-body", this).text(updateContent())
我知道这会起作用:
$("#panel1 .panel-body").text(updateContent())
因此,我尝试在构建ID的同一循环中动态构建该选择器,但是使用所有单引号,双引号和加号,我只是无法获取JavaScript来正确解析行。
我敢肯定解决方案很简单,但是我的眼睛在交叉,我看不到它。
假设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>
尝试这个。
$(this).parent().prev().html("updated content");
您已经很接近了,而不是直接使用this
,而是需要首先使用closest
查找父面板:
$(".panel-body", $(this).closest('div.panel')).text(updateContent())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.