不能在Javascript函数中传递变量

Cant pass variable in Javascript function

本文关键字:变量 函数 Javascript 不能      更新时间:2023-09-26

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

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>';
表 += "+ "+ "点击这里" +"

" + ";

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>');