[英]jQuery How to change text on second element?
How to change h1 text on h1 element on second div (parent2) when click button with jQuery. 当使用jQuery单击按钮时,如何在第二个div(parent2)的h1元素上更改h1文本。 Thanks!
谢谢!
<div id="parent1">
<h1 class="child">Hello World</h1>
</div>
<div id="parent2">
<h1 class="child">Hello World</h1>
</div>
<div id="parent3">
<h1 class="child">Hello World</h1>
</div>
<button>Change</button>
To expand upon Kind user 's answer: 扩展对种类用户的回答:
$('button').on('click', function() {
//kind user's code here//
$('#parent2 .child').text('text');
});
You can do something like this: 您可以执行以下操作:
<div id="parent1">
<h1 class="child">Hello World</h1>
</div>
<div id="parent2">
<h1 class="child">Hello World</h1>
</div>
<div id="parent3">
<h1 class="child">Hello World</h1>
</div>
<button id="changeTextButton">Change</button>
And the JavaScript part: 和JavaScript部分:
$(document).ready(function () {
$('#changeTextButton').click(function () {
$('#parent2 .child').text('Custom text');
});
});
EDIT : The above answers with 编辑 :以上答案
$('button').on('click', function () {
will create the same event for each button on your page. 会为页面上的每个按钮创建相同的事件。
Considering you want a solution based on the position, aka first h1 and second div , and not based on classes and IDs, then you have : 考虑到您需要基于位置(也就是第一h1和第二div )而不是基于类和ID的解决方案,则您有:
$('div:nth-child(2) > h1').text('your text');
But this is just to show how it's done to select by position, @Kinduser's answer is preferable. 但这只是为了显示如何按位置选择,@ Kinduser的答案是可取的。
And to trigger the button click, refers to @splitwire's indication: 并触发按钮单击,请参阅@splitwire的指示:
$('button').on('click', function() {
$('div:nth-child(2) > h1').text('your text');
});
$('#example button').first().click(function () { $('#example div:nth-child(2) > h1').text('your text'); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="example"> <div> <h1>Hello World</h1> </div> <div> <h1>Hello World</h1> </div> <div> <h1>Hello World</h1> </div> <button>Change</button> </div>
Try to do something like that. 尝试做类似的事情。
$('button').on('click', function() {
$('#parent2 .child').html('some text here');
});
$('div:nth-child(2) > h1').text('your new text here');
$('div:nth-child(2)) //2 is the index no of div you can change as you required. like 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.