无法在Javascript函数中传递变量

时间:2014-11-17 16:04:22

标签: javascript

我正在构建一个字符串并用它创建一个表:

table += '<td>'+ '<a href="#" onclick="portal_openModalDialog();" >'+ oListItem.get_item('Title') +'</a>'  + '</td>' 

单击该链接时,该功能将触发。

我需要在函数VarTest()中传递一些Javascript变量,所以我编写了代码:

table += '<td>'+ '<a href="#" onclick="portal_openModalDialog('+ VarTest + ');" >'+ oListItem.get_item('Title') +'</a>'  + '</td>' 

但没有任何反应,我尝试过各种各样的选择,但没有任何作用。

这有效(用+)但是没有任何东西可以通过。

table += '<td>'+ '<a href="#" onclick="portal_openModalDialog('+')" >'+ oListItem.get_item('Title') +'</a>'  + '</td>'


var VarTest = "my text";
function portal_openModalDialog(Title) {
    alert(Title);
}

有什么想法吗?

更新:(这现在适用于单个参数)

table += '<td>'+ '<a href="#" onclick="portal_openModalDialog1(&quot;'+oTitle+'&quot;)" >'+ oListItem.get_item('Title') +'</a>'  + '</td>';

但如果我传递2个参数则不行:

table += '<td>'+ '<a href="#" onclick="portal_openModalDialog1(&quot;'+oTitle,oDescription+'&quot;)" >'+ oListItem.get_item('Title') +'</a>'  + '</td>';

html在屏幕上呈现:

<a href="#" onclick="portal_openModalDialog1(&quot;Bank of England</tr><tr><td><img src='../Style Library/Icons/Noticeboard_News.png' /></td><td><a href="#" onclick="portal_openModalDialog1(&quot;Investor centre - Reed Elsevier</tr><tr><td><img src='../Style Library/Icons/Noticeboard_News.png' /></td><td><a href="#" onclick="portal_openModalDialog1(&quot;This is some news</tr></table> </body>

这是html页面的源代码(无法理解为什么它无法正确呈现):

table += '<td>'+ '<a href="#" onclick="portal_openModalDialog1(&quot;'+oTitle+'&quot;)" >'+ 'click here' +'</a>'  + '</td>';

表格+ =''+''+'点击此处'+''+'';

1 个答案:

答案 0 :(得分:1)

onclick属性的内容被解析为JavaScript。你可以传递变量,不涉及任何魔法:

<script>
    var myVar = 'foo';
    function myFunction(aVar) {
        alert('The variable: ' + aVar);
    }
</script>

<button onclick="myFunction(myVar)">Click me</button>

您可以传递多个变量,只需确保逗号(,)是结果HTML的一部分,而不是原始JavaScript代码中的逗号:

<script>
    var myFirstVar = 'foo';
    var mySecondVar = 'bar';
    function myFunction(aVar, anotherVar) {
        alert('The first variable: ' + aVar + ', and the second: ' + anotherVar);
    }
</script>

<button onclick="myFunction(myFirstVar, mySecondVar)">Click me</button>

如果你想在页面中生成按钮,并且你确定你的变量是字符串,你可以继续引用参数:

document.write('<button onclick="myFunction(&quot;' + myFirstVar + '&quot;, &quot;' + mySecondVar + '&quot;)">Generated button 1</button>');

但是,直接传递变量更容易且更不容易出错:

document.write('<button onclick="myFunction(myFirstVar, mySecondVar)">Generated button 2</button>');