2015-10-05 68 views
-2

我有兩個for循環的功能是這樣的:功能(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"; 
    } 
} 

然後我在另一個函數調用測試()

function test() { 
    displayinventorynone(); 
    displayblock(); 
} 

把這兩個功能現在,當我使用函數「測試」與一個onclick html屬性它does not真的工作。 基本上只有兩個函數中的一個正在執行。 而且它始終是最頂級的,所以在這種情況下,它將是「displayinventorynone」。 雖然「displayblock」根本沒有執行。

將「displayblock」放在頂端意味着只有displayblock正在執行,而另一個功能不是。

這是怎麼發生的?

$ amount在php文件中被定義爲10,而$ amount2應該是5或者其他值。 這兩個元素都會生成10或5次。

+0

除非你沒有從php變量中獲取值,那麼它確實不是php相關的,不應該被標記爲這樣。 – Epodax

+0

使用警報或控制檯日誌來調試流程 –

回答

0

它可能拋出displayinventorynone()一個例外,因爲有沒有您指定的ID的元素。如果您使用chrome,請嘗試按Ctrl + Shift + I打開開發者控制檯,然後單擊頂部的控制檯。它會告訴你那裏的錯誤。

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> 
+0

嗯,我沒有在我的代碼中使用「none」和「not」這個錯誤。我會用這段代碼試一試。 – Shigetora

+0

好的我的樣品適合你嗎? – rocky