jQuery如何获取子元素中链接的href并在其他地方使用它
我的页面底部有一个链接,我给它分配了一个IDjQuery如何获取子元素中链接的href并在其他地方使用它,jquery,parent-child,Jquery,Parent Child,我的页面底部有一个链接,我给它分配了一个ID <a id="nbwalink" class="learn-more"> Learn more </a> …从RSS链接中窃取链接并将其应用于“了解更多”按钮。有没有办法做到这一点,我不能让它工作=T您正试图从p元素中读取href——一个实际上不存在的元素,因为.rssincl itemtitle是p元素,它唯一的子元素是a),如果它存在,它就不会有href。您需要从a元素中读取它: var nbwahref = $("
<a id="nbwalink" class="learn-more">
Learn more
</a>
…从RSS链接中窃取链接并将其应用于“了解更多”按钮。有没有办法做到这一点,我不能让它工作=T您正试图从
p
元素中读取href
——一个实际上不存在的元素,因为.rssincl itemtitle
是p
元素,它唯一的子元素是a
),如果它存在,它就不会有href
。您需要从a
元素中读取它:
var nbwahref = $("div[id^=rssincl-box-]")
.first()
.find(".rssincl-itemtitle a")
.attr("href");
$("#nbwalink").attr("href", nbwahref);
分解那个大的表达:
div
s,id以“rssincl-box”开头.rssincl itemtitle
元素中查找a
元素,该元素位于div
href
(attr
仅返回集合中第一个匹配项的属性)您的选择器错误,因为
p
不是rssincl itemtitle
元素的子元素,p
是rssincl itemtitle
元素,您需要找到p
元素的子元素
var nbwahref = $('.rssincl-content .rssincl-itemtitle:first a').attr('href');
$('#nbwalink').attr('href',nbwahref);
你试过这样的吗
var nbwahref = $('.rssincl-itemtitle').find('a').eq(0).attr('href');
$('#nbwalink').attr('href', nbwahref);
会发生什么?请拉小提琴。
.children('p')。eq(0)
获取一个
,它既不存在也没有href
。尝试var nbwahref=$('.rssincl itemtitle a').eq(0.attr('href')代码>。我在发布此内容后立即看到了P标记。FacePalm Pietu1998在我的原始帖子下发表的评论是我使用的,而且有效。这也是一个问题,因为我在Wordpress中使用美元符号作为jQuery的前缀,这不起作用,我没有提到。Wordpress要求jQuery实际上在任何jQuery函数之前加上“jQuery”。jQuery(document).ready(函数(){var nbwahref=jQuery('.rssincl itemtitle a').eq(0).attr('href');jQuery('#nbwalink').attr('href',nbwahref);});
var nbwahref = $('.rssincl-content .rssincl-itemtitle:first a').attr('href');
$('#nbwalink').attr('href',nbwahref);
var nbwahref = $('.rssincl-itemtitle').find('a').eq(0).attr('href');
$('#nbwalink').attr('href', nbwahref);