[英]access to element in parent div with javaScript?
Hi I want to access all function just do in a div ! 嗨,我想访问所有功能,只是在div中做! for Example :
例如 :
<div class="ow_chat_dialog" id="main_tab_contact_11">
<iframe id="myframe"></iframe>
<button onclick="sersrc()"></button>
</div>
<div class="ow_chat_dialog" id="main_tab_contact_12">
<iframe id="myframe"></iframe>
<button onclick="sersrc()"></button>
</div>
<div class="ow_chat_dialog" id="main_tab_contact_13">
<iframe id="myframe"></iframe>
<button onclick="sersrc()"></button>
</div>
14
15
16
.
.
....
<script>
function setscr(){
document.findviewbyid("myframe").src="hrl..."
}
</script>
in this code i can create some div with one class name and id... But when i click on any button the first iframe change ! 在此代码中,我可以使用一个类名和ID创建一些div ...但是,当我单击任何按钮时,第一个iframe都会发生变化! if i want just change the sibling iframe !
如果我只想更改兄弟iframe的话! ** just use javaScript , Not Jquery .
**仅使用javaScript,而不使用Jquery。
Don't use ids, they must be unique. 不要使用ID,它们必须是唯一的。 Use classes instead:
改用类:
<div class="ow_chat_dialog" class="main_tab_contact_13">
<iframe class="myframe"></iframe>
<button onclick="sersrc(this)"></button>
</div>
Then let sersrc
know which button was clicked by passing button reference. 然后,通过传递按钮引用,让
sersrc
知道单击了哪个按钮。 From there you can find sibling iframe like this for example: 在这里,您可以找到类似的兄弟iframe,例如:
function setscr(obj) {
obj.parentNode.querySelector(".myframe").src = "hrl..."
}
If you are sure that iframe is going to be always immediately before the button then you can simply do 如果您确定iframe始终位于按钮之前,那么您只需
obj.previousElementSibling.src = "hrl..."
(course this is less reliable since depends on structure). (这当然不太可靠,因为取决于结构)。
var els = document.querySelectorAll('.ow_chat_dialog > button'); function handler () { this.previousElementSibling.src = "//stackoverflow.com"; } for (var i=0; i<els.length; ++i) els[i].addEventListener('click', handler);
<div class="ow_chat_dialog"> <iframe id="myframe"></iframe> <button></button> </div> <div class="ow_chat_dialog"> <iframe id="myframe"></iframe> <button></button> </div> <div class="ow_chat_dialog"> <iframe id="myframe"></iframe> <button></button> </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.