Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/vb.net/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
jQuery如何获取子元素中链接的href并在其他地方使用它_Jquery_Parent Child - Fatal编程技术网

jQuery如何获取子元素中链接的href并在其他地方使用它

jQuery如何获取子元素中链接的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 = $("

我的页面底部有一个链接,我给它分配了一个ID

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