本文介绍了在javascript中附近的兄弟姐妹的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个DIV结构,在某个地方有一个锚标签。点击链接后,我需要获取父 div
中另一个 span
元素的值,然后执行某些操作, (说,提醒它)。 html是这样的:
...
< div id =div1>
...
< span>这是reqd< / span>
...
< a href =#>点击我< / a>
...
< / div>
...
整个 div
在页面中重复多次。
当我点击 a
我想提醒这是reqd。
可以像这样搜索HTML吗?
解决方案
单跨元件,应该很简单。只需点击链接即可调用myFunction(this),并按如下操作DOM:
function myFunction(currObj){
var parentofSelected = currObj.parentNode; //给父DIV
var children = parentofSelected.childNodes;
for(var i = 0; i< children.length; i ++){
if(children [i] .tagName =span){
myValue = children [i]值;
break;
}
}
alert(myValue); //只是为了测试
} // end function
希望这个工程。它为我做了!
I have a certain DIV structure with an anchor tag in between somewhere. On click of the link, I need to fetch the value of another span
element within the parent div
and do something, (say, alert it).
The html is like this :
...
<div id="div1">
...
<span>This is reqd</span>
...
<a href="#">Click Me </a>
...
</div>
...
The entire div
is repeated many times in the page.When I click on the a
I want to alert "This is reqd".
Can the HTML be searched like this?
解决方案
For a single span element, it should be pretty easy,. Just call a myFunction(this) on click of the link and manipulate the DOM like this :
function myFunction(currObj){
var parentofSelected = currObj.parentNode; // gives the parent DIV
var children = parentofSelected.childNodes;
for (var i=0; i < children.length; i++) {
if (children[i].tagName = "span") {
myValue= children[i].value;
break;
}
}
alert(myValue); // just to test
} // end function
Hope this works. It did for me !!
这篇关于在javascript中附近的兄弟姐妹的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!