繁体   English   中英

无法在动态生成的HTML中调用javascript函数

[英]Not able to call javascript function in dynamically generated HTML

我无法使用动态生成的HTML代码中的参数调用javascript函数。

当我没有传递任何参数时,相同的函数被成功调用,但是使用参数函数调用失败。 不确定它是否是语法错误。

下面是我的代码:

    <!DOCTYPE html>
    <html>
        <body>

            <p>Click the button to call a function with arguments</p>
            <button onclick="myFunction('Harry Potter','Wizard')">Try it</button>

            <script>
            function myFunction(name,job) {
                var name="prasad";
                var str='<a href="#" onclick="javascript: fun('+name+')">link</a>';
                document.write(str);
            };

            function fun(id1) {
                alert("fun menthod "+id1);
            }
            </script>
        </body>
    </html>

如果我没有传递参数,它会被成功调用。

删除此行,因为变量名称与参数名称相同

var name="prasad";
<!DOCTYPE html>
<html>
<body>
<div id="next">
<p>Click the button to call a function with arguments</p>
<button onclick="myFunction('Harry Potter','Wizard')">Try it</button>
</div>
<script>
function myFunction(name,job)
{
var a='"';
a=a+name+a;
var str="<a href='#' onclick='fun("+a+")'>link</a>";
document.getElementById('next').innerHTML=str;
}
function fun(id1)
{
alert("fun menthod "+id1);
}
</script>
</body>
</html>

这里: var name="prasad"; 你改变'name'参数的值可能这是你的问题。 尝试删除此行并查看输出。

将名称更改为:

var name="'prasad'";

我在JS Console中看到语法错误。

暂无
暂无

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

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