调用一个位于字符串内部的JavaScript函数,并将params与一个变量连接起来

Calling a JavaScript function, which is inside a string, and concatenating params with a variable?

本文关键字:一个 params 并将 连接 起来 变量 内部 字符串 调用 JavaScript 函数      更新时间:2023-11-05

有办法做到这一点吗?我下面的代码不起作用:

$("#template-1")
    .find("span")
    .html("<div id='dialog'><input type='file' onchange='LoadImage(this,"+ 
        canvas +")' id='t1-1-img-header'/><canvas class='dialogCanvas'"+ 
        "width='475' height='250' style='border: 1px solid #555; "+
        "margin-top:10px'></canvas></div>");

在上面的代码中,我试图将"this"和一个在其他地方填充的变量传递给函数"LoadImage"。所有的东西都是动态创建的,并且都在这个长字符串中。

提前谢谢,如果这是一个非常愚蠢的问题,我很抱歉。

编辑:变量"canvas"是一个带有id名称的字符串我要去别的地方。它是画布元素的id

编辑2:很抱歉回复我自己的帖子,但我无法标记对我帮助最大的答案(由@Santiago Rebela提供),所以我在这里复制它。

onchange='LoadImage(this,'""+ canvas +"'")'

事实证明,通过对其进行转义,代码就起了作用。谢谢

下面的答案假设canvas是对HTMLCanvasElement对象的引用

不能将对象引用存储在字符串中。然而,您总是可以存储一些有用的东西来检索对象,比如id,但还有更好的解决方案。

您的主要问题是试图处理内联处理程序,这通常应该避免。

您可以使用jQuery解析HTML字符串,查询创建的DOM元素以查找元素,并将事件处理程序附加到它。

例如

var $myEl = $('<div><input type="text"></div>')
    .find('input')
    .on('change', function (e) {
        console.log(this); //the input
        console.log(canvas); //use the canvas variable (not declared in this example)
        //if you want to access the canvas next to the input in your example
        //you could do $(this).next('canvas');
    });
$('#content').append($myEl); //append your element rather than setting innerHTML