[英]onClick event for Div content
Here is my simple xPage: 这是我简单的xPage:
<?xml version="1.0" encoding="UTF-8"?>
<xp:view xmlns:xp="http://www.ibm.com/xsp/core">
<xp:div
style="border-color:rgb(255,0,0);border-style:solid;border-width:thin"
id="div1" styleClass="divStyleClass1">
<xp:label value="Label" id="label1" styleClass="labelStyleClass">
</xp:label>
<xp:eventHandler event="onclick" submit="false">
<xp:this.script><![CDATA[alert(thisEvent.target.className);
if(thisEvent.target.className=="divStyleClass1"){
thisEvent.target.className="divStyleClass2";
} else {
thisEvent.target.className="divStyleClass1";
}]]></xp:this.script>
</xp:eventHandler>
</xp:div>
</xp:view>
I want to change DIV styleClass by onClick event. 我想通过onClick事件更改DIV styleClass。 And it works fine till I click on any element inside the DIV, eg on the label. 直到我单击DIV内的任何元素(例如在标签上),它都可以正常工作。 Obviously thisEvent.target points to the label object and it fails. 显然,thisEvent.target指向标签对象,并且失败。
So how to fix it so it changes DIV styleClass regardless of where and what you click inside? 那么,如何修复它,从而无论您在何处单击什么,都可以更改DIV styleClass?
A possibility is to use the currentTarget
property of the event rather than target
. 一种可能性是使用事件的currentTarget
属性而不是target
。 currentTarget
contains the node the event handler is attached to. currentTarget
包含事件处理程序附加到的节点。
If that's not sufficient, you might be able to do something like this: 如果这还不够,那么您可以执行以下操作:
var target = thisEvent.target;
while(target != null) {
if(target.nodeName == "DIV") {
break;
}
target = target.parentNode;
}
target
will then contain the nearest ancestor node that is a div or null
. 然后target
将包含最近的div或null
祖先节点。
Instead of checking the target, check the element itself: 而不是检查目标,而是检查元素本身:
var div = document.getElementById("div1");
if(div.className == "divStyleClass1") {
div.className = "divStyleClass2";
} else {
div.className = "divStyleClass2";
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.