javascript - 单击网页时如何获取相应的 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 也可以。
解决方案
如果您使用 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(){});
推荐阅读
- list - Haskell 旋转列表列表
- ios - 如何同时检测两组不同的 ibeacon UUID?
- firebase - Firebase Firstore 子集合
- javascript - 如何遍历 array.map 函数中的数组?
- python-3.x - 特定 Outlook 电子邮件的 Python 问题
- javascript - 有没有办法检查字符串中一定数量的大写字符?
- node.js - axios从url获取文件并上传到s3
- swift - UICollectionView 在单独的子视图控制器中的 UITableView 之上
- python - 如何在现有列上使用条件语句来创建新的 pandas 列
- sql-server - 对分组依据和聚合结果的 SQL 查询