我在webform中有多个div,当我点击一个特定的div时,我需要根据div id执行一些任务。
有没有办法在鼠标点击时找到div id?
<table>
<tr>
<td>
<div id="firstdiv">div1</div>
</td>
<td>
<div id="seconddiv">div2</div>
<td>
<td>
<div id="thriddiv">div3</div>
</td>
<td>
<div id="fourthdiv">div4</div>
</td>
</tr>
</table>
&#13;
答案 0 :(得分:3)
请试试这个:
$("table div").click(function() {
var divID = this.id;//Or $(this).attr("id");
//Your code here
});
答案 1 :(得分:2)
$('div').click(function() {
console.log($(this).attr('id'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td>
<div id="firstdiv">div1</div>
<td>
<td>
<div id="seconddiv">div2</div>
<td>
<td>
<div id="thriddiv">div3</div>
<td>
<td>
<div id="fourthdiv">div4</div>
<td>
<tr>
<table>
答案 2 :(得分:1)
click
元素div
个事件
this
引用click-handler
id
element
属性
$('table div').on('click', function() {
console.log(this.id);
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<table>
<tr>
<td>
<div id="firstdiv">div1</div>
</td>
<td>
<div id="seconddiv">div2</div>
</td>
<td>
<div id="thriddiv">div3</div>
</td>
<td>
<div id="fourthdiv">div4</div>
</td>
</tr>
</table>
&#13;
答案 3 :(得分:0)
如果你想在执行某个功能时点击div,从ID调用,这就是代码:
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
$(document).ready(function () {
$('#firstdiv').click(function(){
/*I add alert for the example, but here is where you put your code*/
alert($(this).attr('id'));
});
</head>
<body>
<div id="firstdiv">div1</div>
</body>
此外,这是与jquery中的函数click()的信息链接,有关于如何在元素的不同事件中使用它的示例:https://api.jquery.com/click/
示例调用表中的div:
$("table div").click(function(){
/*I add alert for the example, but here is where you put your code*/
alert($(this).attr('id'));
});
使用标记div调用示例:
$('div').click(function() {
/*I add alert for the example, but here is where you put your code*/
alert($(this).attr('id'));
});
- 体
<table>
<tr>
<td><div id="demo1"></td>
</tr>
</table>
答案 4 :(得分:0)
这是一个简单而有效的答案
<div id="someId" onclick="somefunction(this.id)">
Click me
</div>
<script>
function somefunction(id){
alert(id);
}
</script>