简体   繁体   English

Javascript-HTC行为对新创建的元素没有影响

[英]Javascript - htc behavior has no effect on newly created elements

I'm trying to identify objects in javascript. 我正在尝试识别javascript中的对象。 My problem is, that msie DOM nodes are not instances of any Object descendant, so I cannot set or get property on such an instance. 我的问题是,msie DOM节点不是任何对象后代的实例,因此我无法在此类实例上设置或获取属性。 I'm trying to make a workaround for that with htc behaviors (only nodes with style can have behavior, so this is a half solution, but better than nothing): 我正在尝试使用htc行为解决该问题(只有具有样式的节点才能有行为,所以这是一个半解决方案,但总比没有好):

identity.htc: identity.htc:

<PUBLIC:COMPONENT>
<script type="text/javascript">
for(property in Object.prototype)
{
    element[property]=Object.prototype[property];
}
</script>
</PUBLIC:COMPONENT>

test.html: test.html:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>javascript identity workaround</title>

<!--[if IE]>
<style type="text/css">
*{behavior:url(identity.htc)}
</style>
<![endif]-->

<script type="text/javascript">

(function ()
{
    var i=0;
    var table={};
    Object.prototype.identity=function ()
    {
        if (!this.__hashcode__)
        {
            this.__hashcode__=++i;
            table[i]=this;
        }
        return this.__hashcode__;
    };
    Object.identify=function (i)
    {
        return table[i];
    };
})();

window.onload=function ()
{
    var body=document.getElementsByTagName("body")[0];
    var existingElement=document.getElementById("existingElement");
    var newElement=document.createElement("div");
        newElement.addBehavior("identity.htc");
    alert(body.identity()); //1
    alert(existingElement.identity()); //2
    alert(newElement.identity()); // expected: 3, real: method not supported
};

</script>
</head>
<body>
    <div id="existingElement"></div>
</body>
</html> 

My problem is, that I cannot use the identity method on the newly created elements. 我的问题是,我不能在新创建的元素上使用标识方法。 I tried to add the behavior with the addBehavior method, but it didn't help. 我试图用addBehavior方法添加行为,但这没有帮助。 Has somebody a solution for this? 有人对此有解决方案吗?

我得到了解决方案:

<PUBLIC:COMPONENT lightWeight="true">

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM