简体   繁体   English

如何使用JavaScript返回DOM元素的ID,而不是元素的值

[英]How do I return the id of a DOM element using javascript, not the value of the element

I'm using backbone. 我正在使用骨干。 In my template I have ---- 在我的模板中,我有----

<a href="#" id='<%= member.get("person").id%>'><%= member.get('person').name%></a>

The id is dynamically set. ID是动态设置的。 I need to use the id as a variable to make a JSON call. 我需要使用id作为变量来进行JSON调用。

I've tried a few things - 我已经尝试了几件事-

$('a').click(function(){
        var memberId = $(this).attr("id");
        console.log(memberId);
    })

or 要么

$('a').click(function(){
        var ID = this.attr('id');
        console.log();
    })

and a couple other variations. 以及其他一些变化。

Suggestions? 建议?

Thanks for all the responses. 感谢您的所有回复。

I should have mentioned that I was trying these things in the document ready just to see if it would work. 我应该提到我正在尝试在文档中准备这些事情,只是想看看它是否可以工作。 My bad, this is my first post on here. 不好,这是我在这里的第一篇文章。 Ultimately, the function should be in my view (I think). 最终,该功能应该在我看来(我认为)。 So it should look more like this - 所以它看起来应该更像这样-

memberId: function(event){
    $(this).attr('id');
}

Which, again is not working..... 哪个又不起作用.....

var memberId = $(this).attr("id");

Your first example here should work. 您的第一个示例应该可以工作。

this.id 

should also work. 应该也可以。

If you're not seeing output its possible that your id is being set to the empty string. 如果没有看到输出,则可能是您的id被设置为空字符串。 Maybe try prepending some text to test it? 也许尝试在文本前面添加测试内容?

console.log("ID: "+this.id);

the first version should work, I have a small comment about your code though. 第一个版本应该可以,但是我对您的代码有一点评论。 Try not using this if you can. 如果可以,请尝试不使用此功能。 Jquery passes the event object as a parameter to the event handler, so you can get a reference to the dom element that triggered this event through something like jQuery将事件对象作为参数传递给事件处理程序,因此您可以通过以下方式获取触发该事件的dom元素的引用:

$('#test').click(function(el){console.log("here: "+$(el.target).attr('id'))}) strong text $('#test')。click(function(el){console.log(“ here:” + $(el.target).attr('id'))}) 强文本

thanks again for your speedy responses. 再次感谢您的迅速答复。

The following code works - 以下代码有效-

memberId: function(event){
    memberId = this.model.get('id');
    console.log(memberId);
}

again, I'm using backbone. 再次,我正在使用骨干网。 So the above is a method in a view. 因此,以上是一种视图方法。 below is the necessary piece 下面是必要的一块

this.model.get('id');

i imagine this... 我想像这个

this.get('id');

should work in the document ready. 应该在准备好的文档中工作。

I'll try to be more clear in the future. 以后我会更清楚。 thanks again... 再次感谢...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM