如何运行data-dojo-attach-event?

时间:2017-02-02 15:07:01

标签: javascript javascript-events dojo

我尝试以编程方式添加domNode后运行该事件:

<a href="javascript:void(0)" data-dojo-attach-event="click:openRegistration">Register</a>

首次加载页面时,Dojo不会解析此事件,因为稍后会添加该页面。即使在运行

之后
parser.parse();

事件未运行。如何让这个事件运行?

3 个答案:

答案 0 :(得分:2)

您不希望dojo解析器对页面进行两次解析:它将冗余地解析并创建已创建的内容并导致混乱。要在解析页面后以编程方式添加节点,请查看dojo/dom-construct

require(["dojo/dom-construct", "dojo/domReady!"],
    function(domConstruct) {

        var openRegistration = function() {
            alert("foo");
        }

        domConstruct.create("a", {
            innerHTML: "Register",
            click: openRegistration,
            href: "javascript:void(0)"
        }, document.body);
    });

将document.body替换为您要插入节点的父节点,并查看第3个放置选项参数。

答案 1 :(得分:0)

您应该使用onclick:openRegistration代替click:openRegistration

<a href="javascript:void(0)" data-dojo-attach-event="onclick:openRegistration">Register</a>

答案 2 :(得分:0)

如果没有看到你们其余的代码,我就会发现你有一个范围问题。或者您还没有正确设置dom事件 - onClick

您的函数需要成为同一个小部件的一部分,该小部件使用带有继承_TemplatedMixin的attach-events的模板。您使用该attach-event的小部件应该类似于

require([
    'dojo/declare',
    'dijit/_WidgetBase', 
    'dijit/_TemplatedMixin', 
    'dojo/text!myNameSpace/templates/MyWidget.html'
], 
function(declare, _WidgetBase, _TemplatedMixin, template){
    declare('MyWidget', [ _WidgetBase, _TemplatedMixin ], {
        templateString: template, 
        openRegistration: function {
               // do stuff here
        }
    });
});