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

4

我无法在动态生成的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>

如果我不传递参数,它会成功调用。

通常情况下,当你无法在HTML中调用JS时,意味着存在JS错误。请打开JS控制台并查看。 - Noam Rathaus
顺便说一句:它可以在 JSFiddle 上运行 - http://jsfiddle.net/#&togetherjs=wHI6Ep7zgl - Noam Rathaus
我尝试了你的代码,它可以正常工作...(良好的实践:不要声明相同的变量两次:name。它已经被声明为参数。因此,只需赋予新值而无需“var”标记。) - ylerjen
你应该使用innerHTML属性而不是document.write()。 检查这个fiddle: http://jsfiddle.net/NU2yF/ - Vin.AI
4个回答

1
删除此行,因为变量名称与参数名称相同。
var name="prasad";

1
<!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>

感谢大家的迅速回复。 - Aaliya

0
在这里: var name="prasad"; 你改变了 'name' 参数的值,也许这就是你的问题。尝试删除这行代码并查看输出。

0

更改名称为:

var name="'prasad'";

否则我在JS控制台中看到语法错误。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接