Javascript将变量传递给input元素中的内联函数

时间:2018-01-10 09:09:08

标签: javascript html

我试图将一个对象 totalArray 传递给一个输入元素,id = fullReport,这样我就可以在一个函数中使用变量totalArray:printFullReport。

输入元素以字符串形式连接,以便最终可以将其创建到表中。

我无法将totalArrays传递给onclick =“printFullReport('+ totalArray +')”>可能由于字符串连接,在我的控制台中我收到: “未捕获的SyntaxError:意外的标识符”意味着缺失;要么 '  但它似乎对我很好。

所以这是我最初的尝试:

<script type="text/javascript">
console.log(totalArray); //{"1":0,"2":0,"3":54700.33,"4":54700.33,"5":0,"6":0,"7":-54700.33,"8":0,"9":0,"10":0};
var str = "";
str += '<td>
<input id ="fullReport"  
class="button" 
type="button" 
value="Full Report" 
    onclick="printFullReport('+ totalArray+ ')">
    TOTAL (GBP):</td>';
</script>

这是我在阅读并遵循最佳答案后的第二次尝试: Inline onclick JavaScript variable

<script type="text/javascript">
var str = "";
console.log(totalArray) //{"1":0,"2":0,"3":54700.33,"4":54700.33,"5":0,"6":0,"7":-54700.33,"8":0,"9":0,"10":0};

function init(){
    document.getElementById('fullReport').onclick=function(){
        printFullReport(totalArray);
    };
}
window.onload=init;

str += '<td><input id ="fullReport"  class="button" type="button" value="Full Report" onclick="init();">TOTAL (GBP):</td>';
</script>

但现在返回:未捕获的ReferenceError:未定义init。

在javascript字符串中包含html元素时,我可能不理解范围。

1 个答案:

答案 0 :(得分:1)

第二次尝试时,您错过了关闭双引号 "

<script type="text/javascript">

您需要从onclick可以访问的地方分配totalArray。 (现在您在评论中澄清 totalArray不是全局范围的。)

<强>演示

&#13;
&#13;
<script type="text/javascript">
var str = "";
totalArray ={ "1":0,"2":0,"3":54700.33,"4":54700.33,"5":0,"6":0,"7":-54700.33,"8":0,"9":0,"10":0};

//console.log(totalArray) //{"1":0,"2":0,"3":54700.33,"4":54700.33,"5":0,"6":0,"7":-54700.33,"8":0,"9":0,"10":0};

function init(){
    document.getElementById('fullReport').onclick=function(){
        printFullReport(totalArray);
    };
}
window.onload=init;

str += '<td><input id ="fullReport"  class="button" type="button" value="Full Report" onclick="init();">TOTAL (GBP):</td>';
</script>

<input id ="fullReport"  class="button" type="button" value="Full Report" onclick="init();">TOTAL (GBP):
&#13;
&#13;
&#13;