使用JavaScript从onclick获取祖先元素的id
下面提供了我自己的答案 如何获取绑定到特定元素类型的祖先ID?(特殊要求:解决方案使用JavaScript,如果可能,不使用jQuery) 现在我只是开始编写代码,我在:使用JavaScript从onclick获取祖先元素的id,javascript,events,event-delegation,Javascript,Events,Event Delegation,下面提供了我自己的答案 如何获取绑定到特定元素类型的祖先ID?(特殊要求:解决方案使用JavaScript,如果可能,不使用jQuery) 现在我只是开始编写代码,我在: document.onclick = clickHandler; function clickHandler(e){ console.log(e.target); } 我想知道从这里到哪里去获取我正在寻找的具体信息 我的页面上有一系列带有唯一ID的文章标签(box_1、box_2等)。我们的愿望是点击这些文章中的任
document.onclick = clickHandler;
function clickHandler(e){
console.log(e.target);
}
我想知道从这里到哪里去获取我正在寻找的具体信息
我的页面上有一系列带有唯一ID的文章标签(box_1、box_2等)。我们的愿望是点击这些文章中的任何一篇,并找出哪篇文章被点击了。这是因为我想根据点击的内容操纵特定文章的样式和属性
我的逻辑是:
记录点击。
如果单击位于框中\n
操纵设备的尺寸/位置
<article id="box_*n*"></article>
单击事件时:
用css类标记每个div(如果cssclass不包含任何样式,则为事件),然后通过getElementsByClassName()查找所有这些元素
对于每个元素,获取id并继续您的逻辑您真正想要做的是只捕获对文章的点击
var articles = document.querySelectorAll("article");//select all article elements
for(var i = 0; i < articles.length; i++){//iterate set of articles
articles[i].onclick = function(){//assign a click event to each article
var currentArticle = this;//when clicked, you can work with the article element
var currentId = this.id;//when clicked, you can access article properties like id
};
}
var articles=document.querySelectorAll(“文章”)//选择所有项目元素
对于(var i=0;i
看看我的代码,它可能会帮助你
<article id="box_1" onclick="clicked(this)">Box 1 content</article>
<article id="box_2" onclick="clicked(this)">Box 2 content</article>
<article id="box_3" onclick="clicked(this)">Box 3 content</article>
<script>
function clicked(clickedBox) { //get the box clicked
clickedBox.style.fontSize="24px"; //change the font size of the box clicked
}
</script>
框1内容
框2内容
框3内容
单击函数(clickedBox){//单击该框
clickedBox.style.fontSize=“24px”//更改所单击框的字体大小
}
您可以在body元素上放置一个侦听器,然后使用相关的事件对象查找任何祖先文章元素,例如
<body onclick="getArticle(event)" ...>
很酷的解决方案!我喜欢这个逻辑,可以用这个。我在想,有没有可能先获取祖先ID,然后再提取用于文章标签的ID?你能澄清一下吗?只是出于好奇,你的解决方案可能会很好地工作,但我想知道是否允许我构建逻辑,让我1)在任何地方捕捉事件,2)向上冒泡,3)捕获沿途的元素类型,4)停止此类型的元素,5)给我该元素的id 1)它将只捕获在项目元素内部任何位置发生的单击事件2)如果单击项目元素内部的元素,它将冒泡到此单击事件处理程序3)捕获元素类型是通过.parentNode或.children导航DOM所要做的事情4)事件处理程序将位于article元素上5)
此
将引用article元素(因此,此.id
将为您提供该元素的id。code–只有答案不受欢迎。您需要解释您的答案如何解决OP(而不是“阅读代码…”).谢谢你,我会向上投票,但我还没有足够的街头信誉来向上投票。我使用了你的一些逻辑,但不想要while循环的特殊性,相反,我只是使用了一个递归函数。我在原始问题中提供了我的解决方案。
<body onclick="getArticle(event)" ...>
function getArticle(event) {
var target = event.target || event.srcElement;
var article;
if (target) {
article = upTo(target, 'article');
}
if (article) {
// do stuff with article
}
}
// Find first ancestor of el with tagName
// or null if not found
function upTo(el, tagName) {
tagName = tagName.toLowerCase();
while (el && el.parentNode) {
el = el.parentNode;
if (el.tagName && el.tagName.toLowerCase() == tagName) {
return el;
}
}
return null;
}