如何设置我们从 JavaScript 中其他元素的属性返回的值 onclick 函数

how to set the value we are returned from the attribute of other elements onclick function in javascript?

本文关键字:元素 其他 属性 返回 函数 onclick JavaScript 何设置 设置 我们      更新时间:2023-09-26

大家好,任何人都可以帮助我我有一个问题,我创建了这个函数来创建一个按钮并从主按钮获取 t 属性 vaue 并将此值设置为 onclick 事件,按钮将被创建但不起作用

<button id="d" t="Demo();" onclick="CreateAndSetEvents();">click me</button>
<script>
function CreateAndSetEvents(){
var eval;
    var x=document.getElementById('d');
    if(x.hasAttribute("t")){
        eval=x.getAttribute('t');
        var el=document.createElement("input");
        el.setAttribute("type","button");
        el.setAttribute("value","created");
        el.onclick=function(){ eval}//now the value of eval is Demo function but why don't work ?! 
        document.body.appendChild(el);
    }
}
function Demo(){
alert("hello from demo ');
}
</script>

您的代码存在许多问题。

第一

alert("hello from demo ');

应该是

alert("hello from demo ");

您需要将开盘语与结束语匹配

第二个 eval 是 javascript 中的一个保留关键字,所以你真的不应该把它用作变量名。

我强烈建议您在运行代码之前开始使用 JSLint 来清理代码,它会捕获这样的语法错误

第三,在 html 中注册的事件处理程序不应后跟分号。

第四,也是与您的需求最相关的是,当您从按钮 d 获取属性 t 时,您不会获得函数 Demo,而是获得字符串"Demo()",您不能只是将该字符串放入函数中并执行它。

Javascript确实包含一个内置函数,用于将字符串评估为称为eval的代码。但是,使用它是一个非常糟糕的主意。如果有人将一个字符串传递给您的评估,将恶意数据发布到您的服务器,或要求提供敏感信息,该怎么办?Eval是一个巨大的安全威胁。如果你不想使用 eval,你会像这样使用它:

<button id="d" t="Demo()" onclick="CreateAndSetEvents()">click me</button>
<script type="text/javascript">
function CreateAndSetEvents() {
    var f;
    var x = document.getElementById('d');
    if (x.hasAttribute("t")) {
        f = x.getAttribute('t');
        alert(f);
        var el = document.createElement("input");
        el.setAttribute("type", "button");
        el.setAttribute("value", "created");
        el.onclick = function() {
            eval(f);
            };
         //now the value of eval is Demo function but why don't work ?! 
        document.body.appendChild(el);
    }
}
function Demo() {
    alert("hello from demo");
}
</script>

如果你想避免使用eval函数,你可以这样做:

el.onclick = function() {
    window[f].call();
};

然后,您必须在属性中仅使用函数的名称,不带括号。

我认为它比使用 eval 更好,因为它仅限于窗口对象中可用的函数。

var CreateAndSetEvents = function() {
    var f;
    var x = document.getElementById('d');
    if (x.hasAttribute("t")) {
        f = x.getAttribute('t');
        //alert(f);
        var el = document.createElement("input");
        el.setAttribute("type", "button");
        el.setAttribute("value", "created");
        el.onclick = function() {
            //eval(f);
            window[f].call();
            };
         //now the value of eval is Demo function but why don't work ?! 
        document.body.appendChild(el);
    }
};
function Demo() {
    alert("hello from demo");
}
<button id="d" t="Demo" onclick="CreateAndSetEvents()">click me</button>
<div id="output"></div>