首页 > 解决方案 > 单击网页时如何获取相应的 HTML 元素及其索引?

问题描述

我有一个网页。假设我不知道该页面包含一个<p>或任何其他 HTML 标记。该脚本在后台运行,当我单击网页上的任意位置时,如果单击有相应的 HTML 标记,则该脚本将返回该标记及其索引号。

    <!DOCTYPE html>
    <html>
<head>
    <title>Page Title</title>
</head>
<body>
    <p></p>
    <div></div>
    <div></div>
</body>
</html>

现在,当我单击标签 p 时,脚本应返回<p>及其索引。有点像这样:

$("body").click(function(){
/* return the clicked html tag within body and its index*/    
});

为了这:

$("tag name").click(function(){
     // return tag
 });

我需要知道我点击的是哪个标签。但我不知道我要点击哪个标签。

纯 JS 也可以。

标签: javascriptjqueryhtml

解决方案


如果您使用 p 是包含在正文中的标签

$("body").click(function(){
/* return the clicked html tag within body and its index*/    
});

因此,如果您点击,所有孩子都会阅读正文点击

如果你想点击 p 试试看

$('p').on('click',function(){});

并且不要使用

 $("body").click(function(){
    /* return the clicked html tag within body and its index*/    
    });

或者你可以试试click p

 $('body p').on('click',function(){});

推荐阅读