gpt4 book ai didi

jquery - 查找距离单击的按钮最近的

转载 作者:行者123 更新时间:2023-12-01 08:12:55 24 4
gpt4 key购买 nike

$(document).ready(function()
{
$('button').on('click', function()
{
$('.container').children().eq(1).append($('p.important').text());
});
});

<div class="container">
<p>1</p>
<p>2</p>

<button>Lawl, a button.</button>

<p>3</p>
<p class="important">Text to be copied</p>
</div>

我想找到距离我的按钮最近的上部 p 标签。例如,如果我将按钮移动到 <p>1</p> 下,它应该向其附加值。如果我将按钮移动到底部,它应该将附加值添加到 <p>3</p> .

我当前的 HTML 可以吗?

最佳答案

您可以使用nextprev方法。

.next( [selector] ): Get the immediately following sibling of each element in the set of matched elements. If a selector is provided, it retrieves the next sibling only if it matches that selector.

.prev( [selector] ): Get the immediately preceding sibling of each element in the set of matched elements, optionally filtered by a selector.

$('.container button').on('click', function(e) {
e.preventDefault();
var txt = $('p.important').text();
$(this).next('p').append(txt);
});

关于jquery - 查找距离单击的按钮最近的 <p>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12369606/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com