函数中的函数(Javascript)

时间:2015-10-05 10:46:49

标签: javascript

我有两个类似的循环函数:

function displayblock() {
    for (var x = 1; x <= <?php echo $amount; ?>; x++) {
        document.getElementById("something" + x).style.display = "block";
    }
}

function displayinventorynot() {
    for (var x = 1; x <= <?php echo $amount2; ?>; x++) {
        document.getElementById("inventoryslot" + x).style.display = "none";
    }
}

然后我将这两个函数放在另一个名为test()

的函数中
function test() {
    displayinventorynone();
    displayblock();
}

现在,当我使用带有onclick html属性的“test”函数时,它确实无法正常工作。 基本上只有两个函数中的一个正在执行。 它始终是最重要的一个,所以在这种情况下它将是“displayinventorynone”。 虽然“displayblock”根本没有执行。

将“displayblock”放在顶部意味着只执行displayblock而另一个功能没有。

为什么会这样?

$ amount在php文件中定义为10,$ amount2应为5或者其他内容。 这两个元素都会生成10或5次。

2 个答案:

答案 0 :(得分:0)

首先,您的代码中存在错误

function test() {
    displayinventorynone();   // Incorrect Name to call displayinventorynot
    displayblock();
}



function displayblock() {
    for (var x = 1; x <= <?php echo $amount; ?>; x++) {
        document.getElementById("something" + x).style.display = "block";
    }
}

function displayinventorynot() {
    for (var x = 1; x <= <?php echo $amount2; ?>; x++) {
        document.getElementById("inventoryslot" + x).style.display = "none";
    }
}

适用于您的示例代码see comment for details

  First name: <input type="text" name="fname" id="something1" value="John" style="display:none;"><br>
  Last name: <input type="text" name="lname" id="inventoryslot1" value="Doe" style="display:block;"><br>
  <input type="button" value="Submit form" onclick="test();">


<?php

$amount = 10;
$amount2 = 5;
?>

<script>

function test() {

    displayinventorynot();
    displayblock();
}


function displayblock() {
    for (var x = 1; x <= <?php echo $amount; ?>; x++) {
        if(x==1){  // check to avoid TypeError: Cannot read property 'style' of null (no other id exist more than 1)
        document.getElementById("something" + x).style.display = "block";
      }
    }
}

function displayinventorynot() {
    for (var x = 1; x <= <?php echo $amount2; ?>; x++) {
        if(x==1){  // check to avoid TypeError: Cannot read property 'style' of null (no other id exist more than 1)
        document.getElementById("inventoryslot"+x).style.display = "none";
        }
    }
}


</script>

答案 1 :(得分:0)

它可能会在displayinventorynone()中引发异常,因为没有指定id的元素。如果您使用chrome,请尝试按Ctrl + Shift + I打开开发人员控制台,然后单击顶部的控制台。它会在那里显示错误。