繁体   English   中英

将参数传递给动态生成的元素的on click事件

[英]Passing argument to on click event of dynamically generated element

我试图将参数传递给动态生成的元素的onclick事件。 我已经看到了现有的stackoveflow问题,但没有满足我的特定需求。在这个现有问题中,他们正在尝试使用$(this).text();访问数据。 但我不能在示例中使用它。

Click事件不适用于动态生成的元素

在下面的代码片段中,我试图将程序和macroVal传递给onclick事件,但是它不起作用。

onClickTest = function(text, type) {
        if(text != ""){
        // The HTML that will be returned
        var program = this.buffer.program;
        var out = "<span class=\"";
        out += type + " consolas-text";
        if (type === "macro" && program) {
            var macroVal = text.substring(1, text.length-1);
            out += " macro1 program='" + program + "' macroVal='" + macroVal +  "'";
        }
        out += "\">";
        out += text;
        out += "</span>";
        console.log("out " + out);


        $("p").on("click" , "span.macro1" , function(e)
        {
            BqlUtil.myFunction(program, macroVal);
        });

    }else{
        var out = text;
    }
    return out;

};

console.log出来给我这个

<span class="macro consolas-text macro1 program='test1' macroVal='test2'">{TEST}</span>

我已经尝试了this.program和program,但是不起作用。

获得span元素属性的值,因为您将它们包含在html中:

$("p").on("click" , "span.macro" , function(e)
{
  BqlUtil.myFunction(this.getAttribute("program"), 
    this.getAttribute("macroVal"));
});

但是,您的代码中有几处错误。

  • 您在分配给out html中两次指定了class属性,

  • 您使用的单引号不正确(使用' ,不是' ),

  • 属性值的引号混乱:属性值始终使用单引号或双引号

var out = "<span class='";

...

out += "' class='macro' program='" + program + "' macroVal='" + macroVal + ;

...

out += "'>";

  • 根据您计划调用onClickTest ,您可能最终得到p span.macro多个click事件处理程序。

暂无
暂无

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

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