简体   繁体   English

jquery .parents()

[英]jquery .parents()

I've got a list and a link, i want to change the top link: 我有一个列表和一个链接,我想更改顶部链接:

<a class="topLink" href="#">change me</a>

<ul>
    <li><a href="#">link name</a></li>
    <li><a href="#">link name</a></li>
    <li><a href="#">link name</a></li>
    <li><a href="#">link name</a></li>
    <li><a href="#">link name</a></li>
</ul>   

When I click a 'link name' link, I want that text to be applied to the change me link. 当我点击“链接名称”链接时,我希望将该文本应用于“更改我”链接。

How do I do this with jQuery parents? 我如何用jQuery父母做到这一点? or what should I be using? 或者我应该使用什么?

Edit: Sorry, I forgot to say that I will have three of these lists, so three links that have a class of topLink 编辑:对不起,我忘了说我会有三个这样的列表,所以三个链接都有一类topLink

$('ul').delegate('a', 'click', function() {
    $('.topLink').text($(this).text());
});

No need to invoke .parents() here (it wouldn't really work either) 不需要在这里调用.parents() (它也不会真的有效)

by using .delegate() you can do the job by only binding one event handler to the parent ul element. 通过使用.delegate()您可以通过仅将一个事件处理程序绑定到父ul元素来完成工作。 Of course it would be much better if that ul had an id. 当然,如果ul有id,那会好得多。

Ref.: .delegate() 参考: .delegate()
Example: Here 示例: 这里

$('ul li a').click(function () {
    $(".topLink").html($(this).html());
});

It already has a class, I wouldn't use parents since you would then have to get the parent's sibling (maybe jquery should have an uncle reference??? jk). 它已经有一个类,我不会使用父母,因为你必须得到父母的兄弟(也许jquery应该有一个叔叔参考??? jk)。

Using the class would be: 使用该类将是:

$('li a').click( function() {
    $('.topLink').text( $(this).text());
}

If the <ul> and the <a> are adjacent siblings, then trythis: 如果<ul><a>是相邻的兄弟姐妹,那么试试这个:

$('ul').delegate('a','click',function() {
    $(this).closest('ul').prev().text( $(this).text() );
});

This uses jQuery's closest() method to get the first <ul> ancestor, and jQuery's .prev() method to traverse from the <ul> to its previous sibling. 这使用jQuery的 .prev() closest()方法来获取第一个<ul>祖先,并使用jQuery的.prev()方法<ul>遍历到它之前的兄弟。

If the HTML markup is any different from that which you've provided, then you need to give a sample of your actual HTML. 如果HTML标记与您提供的标记有任何不同,那么您需要提供实际HTML的示例。

我更喜欢使用.closest()

the anchor tag you're trying to change isn't in the hierarchy of the LI so the parents() method won't pick it up. 您尝试更改的anchor标记不在LI的层次结构中,因此parents()方法不会将其拾取。 Your best bet would be to either select it by id or class and change the html value that way. 您最好的选择是通过id或class选择它并以这种方式更改html值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM