找到最接近的< p>点击按钮 [英] Finding closest <p> to the clicked button

查看:49
本文介绍了找到最接近的< p>点击按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  $(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,一个按钮。< / button>

< p> 3< / p>
< p class =important>要复制的文字< / p>
< / div>

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



我的当前HTML有可能吗?

解决方案

你可以使用 next prev 方法。


.next( [selector]):获取匹配元素集中每个元素的紧随其后的兄弟。如果提供了一个选择器,只有当它与那个选择器匹配时,它才会检索下一个兄弟。




< blockquote>

.prev([selector]):获取匹配元素集中每个元素的前一个兄弟,可选择由选择器过滤。




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


$(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>

I want to find the closest upper p tag to my button. For example, if I move button under <p>1</p>, it should append values to it. If I move my button to bottom, it should add append values to <p>3</p>.

Is it possible with my current HTML?

解决方案

You can use next or prev method.

.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);    
});

这篇关于找到最接近的&lt; p&gt;点击按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆