javascript jquery-将单击的链接的 id 存储在变量中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7218278/
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- store id of clicked link in variable
提问by cbr0wn
This should be basic, but for some reason its not working for me. I just want to store the id when a link that has a certain class is clicked in a variable so as an example:
这应该是基本的,但由于某种原因它对我不起作用。我只想在变量中单击具有某个类的链接时存储 id,例如:
<a href="#" id="this_id_here" class="only_this_class">Some link</a>
I would want jquery to get the id of the link above and store it in a variable. I have tried $this.attr("id") and $this.id, but non of this worked.
我希望 jquery 获取上面链接的 id 并将其存储在一个变量中。我试过 $this.attr("id") 和 $this.id,但没有一个有效。
This is what I have for the jquery:
这就是我对 jquery 的看法:
$(".only_this_class").click(function() {
var clickedId= $(this).attr("id");
alert(clickedId);
});
I just get "undefined" every time.
我每次都得到“未定义”。
采纳答案by Naveed
I removed the space between this
and _class
in class="only_this _class"
and it is working for me.
我删除了空间之间this
,并_class
在class="only_this _class"
它对我来说有效。
Please have a look at jQuery Selectors
请看一下jQuery 选择器
If you have two classes in your HTML then the syntax is different:
如果您的 HTML 中有两个类,则语法不同:
$('.classA.classB')
Have a look at How can I select an element with multiple classes?
回答by gengkev
NAVEED is right, if you remove the space it works, because if there is a space HTML will put two classes on the element: only_this and _class.
NAVEED 是对的,如果你删除空格它会起作用,因为如果有空格 HTML 将在元素上放置两个类:only_this 和 _class。
If you arein fact looking for two different classes, you should replace the space with a dot to make it work properly, as in $(".only_this._class")
如果你是其实找两个不同类别,您应以点代替空间,使其正常工作,如$(".only_this._class")
回答by ShankarSangoli
$(".only_this _class")
this selector will look for _class
tag in .only_this
element. May you are looking for $(".only_this")
which will select element which has this class. Try this.
$(".only_this _class")
此选择器将_class
在.only_this
元素中查找标记。可能您正在寻找$(".only_this")
哪个将选择具有此类的元素。试试这个。
$(".only_this").click(function() {
var clickedId= $(this).attr("id");
alert(clickedId);
});