2015-05-04 47 views
0

謙遜appologies,如果這是一個愚蠢的問題,但我不能爲我的生活弄清楚這裏有什麼問題。PHP Javascript無法訪問PHP模式外的回顯元素ID

我有PHP內模式的呼應元素:

echo'<select name="picks" id="winner">'; 
      echo'<option value="'.$row['team1'].'">'.$team1.'</option>'; 
      echo'<option value="'.$row['team2'].'">'.$team2.'</option>'; 
    echo'</select>'; 

現在 PHP 我嘗試做一個基本的JavaScript GET:

document.getElementById("winner"); 

然而elemnt不可訪問我在這裏錯過了什麼,難道不可能得到迴應的元素ID?

+0

是的,這是可能的,但你想用這個元素做什麼? – xNeyte

+0

你究竟是什麼意思的「外部」的PHP? –

+0

只需將它分配給一個變量,然後做一些基本的事情,如獲得其選定的值 – Marilee

回答

2

你應該確保你的DOM元素進行選擇之前至少已經加載。如果你可以使用jQuery,那麼這是爲下那樣容易,你可以把這個腳本在head部分,或任何地方body

$(document).ready(function() { 
    // Perform any selects on the DOM 
}); 

JS

<script src="//code.jquery.com/jquery-1.9.1.min.js"></script> 
<script> 
$(document).ready(function() { 
    // The DOM is loaded and ready to be selected 
    var select = document.getElementById("winner"); 
    var optionText = select.options[select.selectedIndex].text; 
    var optionValue = select.options[select.selectedIndex].value; 
}); 
</script> 

中當然,你也可以執行DOM選擇使用jQuery:


如果$row$team1$team2沒有定義,你有PHP錯誤和通知開啓另一種可能性,那麼HTML將呈現像這樣:

<select name="picks" id="winner"><b>E_NOTICE : </b> type 8 -- Undefined variable: row -- at line 4<br /><b>E_NOTICE : </b> type 8 -- Undefined variable: team1 -- at line 4<br /> 
    <option value=""></option><b>E_NOTICE : </b> type 8 -- Undefined variable: row -- at line 5<br /><b>E_NOTICE : </b> type 8 -- Undefined variable: team2 -- at line 5<br /> 
    <option value="" selected="selected"></option> 
</select> 

但是,如果你有PHP錯誤和警告變成關閉,您會看到類似下面的內容:

<select name="picks" id="winner"> 
    <option value=""></option> 
    <option value="" selected></option> 
</select> 

如果您無法訪問選定HTML中的選項值(因爲它們是空的),這將是開始調查的好步驟。

0

使用jQuery你可以嘗試以下操作:

// I have used mouse down event for demo purpose. 
$(document).delegate('#winner', 'mousedown', function() 
{ 
    alert('hi'); 
}); 
0

嘗試訪問選擇的ID的 我給一個演示小提琴 Demo fiddle document.getElementById("winner").value;

0

呼應JS代碼是共同的價值,但也有這些可能性:

1-您在創建該元素之前將document.getElementById("winner");放入。

2 - 腳本標記中存在語法錯誤,導致錯誤,您的選擇無法正常工作。

0

,因爲PHP的一部分將頁面加載,你可以簡單地做這樣的前可用:

<?php 
$row['team1']=1;$team1='India';$row['team2']=2; $team2='SA'; 
echo'<select name="picks" id="winner">'; 
echo'<option value="'.$row['team1'].'">'.$team1.'</option>'; 
echo'<option value="'.$row['team2'].'">'.$team2.'</option>'; 
echo'</select>'; 
    ?> 
<script> 

console.log(document.getElementById("winner"));//see this in console. 

</script>