使用javascript获取div id [英] Get div id using javascript

查看:100
本文介绍了使用javascript获取div id的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是一些HTML:

<div class="results">
  <div id="1">something</div>
  <div id="2">something else</div>
  <div id="3">blah blah blah</div>
  <div id="4">etc</div>
</div>

现在如果我可以使用jQuery调用它:

Now if I can call this using jQuery:

var div = $(".results > div");
div.click(function()
{
  alert(this.childNodes[0].nodeValue);
});

当点击div时,它会调出一个警告框,说明div中的什么(从列表中上面:'某事','别的','等等等等'或'等')。有谁知道如何让它提醒div(在这个例子中,1,2,3或4)div而不是节点内的信息?

When clicking on a div, it will call an alert box saying whats in the div (from the list above: one of 'something', 'something else', 'blah blah blah' or 'etc'). Does anyone know how I can get it to alert the id (in this example, 1, 2, 3 or 4) of the div rather than the information within the node?

谢谢

推荐答案

在事件处理程序中,指的是点击的。您可以访问其 id property [MDN]

Inside the event handler, this refers to the clicked div. You can access its id property [MDN]:

alert(this.id);

注意: HTML4不允许 id s以数字开头。

Note: HTML4 does not allow ids to start with digits.

PS:选择器应为 $(。results> div ) (已修复)

这篇关于使用javascript获取div id的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆