2015-05-04 48 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>