Mootools - 为什么不跑?

时间:2010-09-28 07:57:04

标签: mootools

你可以测试我的代码,当我点击按钮时,我们会得到2个链接

点击第一个链接,而不是提醒

点击第二个链接,显示提醒

为什么第一个链接没有提醒,如何提醒?

<html>
<head>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">google.load("mootools", "1.1.2");</script>
<script>
    window.addEvent('domready', function(){
        $('button').addEvent('click', function(){
            $('content').innerHTML = $('test').innerHTML;
        });
    });

</script>
</head>
<body>
<input id="button" type="button" name="button" value="Click"/>
<div id="content">
</div>
<div id="test">
    <script>
        function test(){
            $('a-content').addEvent('click', function(){
                alert(1);
            });
        }
        window.addEvent('domready', function(){
            test();
        });
    </script>
    <a id="a-content" href="#">CLICK HERE</a>
</div>
</body>
</html>

1 个答案:

答案 0 :(得分:1)

除非您使用事件委派,否则在动态注入HTML时不会转移事件。如果您不使用事件委派,则事件将仅在原始元素上。见http://mootools.net/docs/more/Element/Element.Delegation

你需要做这样的事情。 $('body')。addEvent('click:relay(#a-content)',function(){...});主体将捕获click事件并将其委托给id为“a-content”的任何元素。

同样通过设置内容,例如$('content')。innerHTML = $('test')。innerHTML;您将拥有ID为“a-content”的重复元素,这是错误的。 HTML id应该是唯一的。尝试对您将重复使用的内容进行分类。