jQuery jquery在children()中获取href

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5298898/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 18:55:49  来源:igfitidea点击:

jquery get href in children()

jquery

提问by Teson

  alert($(this).children().next().html());

returns

返回

  <a href="thelink.php?id=XXXX">click me...</a>

How do I change above statement to grab only the href?

如何更改上述语句以仅获取 href?

Have tried attr('href') but can't get it to work.

已尝试 attr('href') 但无法使其正常工作。

(Yes, jq-noob and no time.)

(是的,jq-noob,没时间。)

//edit - code added:

//编辑 - 添加的代码:

<div class="row">
  <div class="date">
    <h2>27</h2>
    <h3>dec</h3>
  </div>
  <h2><a href="/wpb/index.php?id=4192#4199">the title..</a></h2>
  <p>the description...</p>
</div>

jq invoked by:
$("#threecol .row").click(function() {  
  alert($(this).children().next().href);
});

regards,

问候,

回答by Andrew

Find the attribute value using .attr('href').

使用 .attr('href') 查找属性值。

EDIT: The first anchor within a H2:

编辑:H2 中的第一个锚点:

alert($(this).find('h2 a:first').attr('href'));

You could also reference it via a class if you prefer and use the class in your anchor.

如果您愿意,也可以通过类引用它并在锚中使用该类。

alert($(this).find('.myLink').attr('href'));

回答by SLaks

$(this).children().next()is returning an element that has an <a>inside of it.
To get that <a>'s href, you need to select it, then call .attr('href').

$(this).children().next()正在返回一个有<a>内部元素的元素。
要获取<a>href,你需要选择它,然后调用.attr('href')

You want to write something like

你想写一些类似的东西

alert($(this).find('a:first').attr('href'));

In your case, you may want to write .find('h2 a').

在您的情况下,您可能想要编写.find('h2 a').

回答by Sang Suantak

You can try this:

你可以试试这个:

Edited: alert($(this).find("a").attr("href"));

编辑: alert($(this).find("a").attr("href"));