简体   繁体   English

将JavaScript变量传递到HTML

[英]Passing the JavaScript variable into HTML

My JavaScript code is: 我的JavaScript代码是:

<script type="text/javascript">
     var current = 0;
var cars = new Array(5);
cars[0] = "Audi";
cars[1] = "Bentley";
cars[2] = "Mercedes";
cars[3] = "Mini";
cars[4] = "BMW";
document.getElementById("addCarBtn").onclick = function () {
    if (!(current > cars.length - 1)) {
        document.getElementById("carsDiv").innerHTML += cars[current] + "<br />";
        current++;
    }
}
</script>

I want to display the value of each array item one by one on button click the div. 我想在按钮上单击div逐个显示每个数组项的值。

But when i click the button, the array[0] ie "Audi" is displayed but just for fraction of seconds. 但是,当我单击按钮时,将显示array [0],即“ Audi”,但仅持续几秒钟。 then it disappears and only the button is visible. 然后消失,只有按钮可见。

How about the every method? every方法怎么样?

cars.every( function(c) {
    alert("car: " + c);
});

You can use a loop like:- 您可以使用如下循环:

for(var i=0; i< cars.length;i++)
{
alert(cars[i]);
}

//It will show alert 5 times. //它将显示警报5次。 You'll need to click through ok to traverse all array elements. 您需要单击确定以遍历所有数组元素。 //I think it is what you're thinking, or have I interpreted it wrong. //我认为这就是您的想法,或者我误解了。

// I'm assuming you're completely new to javascript then on your button write onclick="yourFuncName();" //我假设您是javascript的新手,然后在您的按钮上输入onclick =“ yourFuncName();”

function YourfuncName()
{
//Initailze your array here, like you have done or like kamituel has done
// then just print each array element one by one 
for(var i=0; i< cars.length;i++)
{
alert(cars[i]);
}

}

You're almost there. 你快到了。 Since the JS code was located before the HTML, the button element still doesn't exist. 由于JS代码位于HTML之前,因此button元素仍然不存在。 Best just wrap the code with window.onload and it should work: 最好只用window.onload包装代码,它应该可以工作:

window.onload = function() {
    document.getElementById("addCarBtn").onclick = function() {
        if (!(current > cars.length - 1)) {
            document.getElementById("carsDiv").innerHTML += cars[current] + "<br />";
            current++;
        }
    }
};

Live test case . 现场测试用例

Edit: just noticed your button doesn't have type. 编辑:只是注意到您的按钮没有类型。 This means that some browsers might make it a submit button by default, which will cause a page reload. 这意味着某些浏览器可能默认将其设为“提交”按钮,这将导致页面重新加载。 To avoid it, make it a plain button: 为了避免这种情况,请将其设置为普通按钮:

<button id="addCarBtn" type="button">

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

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