单击元素的 jQuery 子元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/359393/
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
jQuery child of clicked element
提问by Tom
I've got a list of links which have a click event attached to them, I need to get the ID from the child A link. So in the example below if I clicked the first list element I'd need google retuned.
我有一个链接列表,其中附加了一个点击事件,我需要从子链接 A 获取 ID。所以在下面的例子中,如果我点击了第一个列表元素,我需要重新调整谷歌。
I've tried '$this a'
but can't quite work out the syntax.
我试过了,'$this a'
但不能完全弄清楚语法。
$("ul li").click(function(event){
$("input").val($(this).html());
});
<ul>
<li><a href="http://www.google.com" id="google">Google</a>
</ul>
回答by smoothdeveloper
I don't see the sample HTML but
我没有看到示例 HTML 但
$(this).find('a:first').attr('id')
would do it (fix a:firstselector if it's not what you meant)
会这样做(如果不是您的意思,请修复a:first选择器)
thisrefer to the element that fired your event
这指的是触发您的事件的元素
回答by Wayne Austin
To make your code a little neater, lets bind triggers with functions like so: (i suggest you give your UL an ID so it is specific to only elements within that UL)
为了让你的代码更简洁,让我们用这样的函数绑定触发器:(我建议你给你的 UL 一个 ID,这样它只特定于该 UL 中的元素)
$('ul li').bind('click', getAnchorId);
The function that is called (getAnchorId) gets the ID attribute of the children element (a) of the clicked element (ul li) and applies it to a variable (anchorId), and to show its getting the correct info I put the result in an alert.
被调用的函数 (getAnchorId) 获取被单击元素 (ul li) 的子元素 (a) 的 ID 属性并将其应用于变量 (anchorId),并显示其获取正确信息,我将结果放入警报。
function getAnchorId() {
var anchorId = $(this).children('a').attr('id');
alert(anchorId);
}
Now u can do what ever u wish with that variable :)
现在你可以用那个变量做任何你想做的事情:)
hope this helps :)
希望这可以帮助 :)