PHP Javascript无法在PHP模式之外访问回显的元素id
谦虚的道歉如果这是一个愚蠢的问题,但我一辈子都搞不清楚这里到底出了什么问题 我在php模式中有一个回音元素:PHP Javascript无法在PHP模式之外访问回显的元素id,javascript,php,Javascript,Php,谦虚的道歉如果这是一个愚蠢的问题,但我一辈子都搞不清楚这里到底出了什么问题 我在php模式中有一个回音元素: echo'<select name="picks" id="winner">'; echo'<option value="'.$row['team1'].'">'.$team1.'</option>'; echo'<option value="'.$row['team2'].'">'.$tea
echo'<select name="picks" id="winner">';
echo'<option value="'.$row['team1'].'">'.$team1.'</option>';
echo'<option value="'.$row['team2'].'">'.$team2.'</option>';
echo'</select>';
但是,元素不可访问。如果我在这里遗漏了什么,是否无法获取回显元素ID?使用JQUERY,您可以尝试以下操作:
// I have used mouse down event for demo purpose.
$(document).delegate('#winner', 'mousedown', function ()
{
alert('hi');
});
尝试访问所选id的值 我正在演示小提琴
document.getElementById(“获胜者”).value代码>重复JS代码很常见,但也有以下几种可能性:
1-您将document.getElementById(“获胜者”)代码>在php创建该元素之前
2-脚本标记中存在语法错误,导致错误,因此您的选择不起作用。由于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>
log(document.getElementById(“获胜者”)//在控制台中可以看到这一点。
在执行元素选择之前,应确保至少加载了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>
但是,如果您关闭了PHP错误和警告,您将看到如下内容:
<select name="picks" id="winner">
<option value=""></option>
<option value="" selected></option>
</select>
如果您无法访问所选HTML中选项的值(因为它们是空的),这将是开始调查的好时机。是的,这是可能的,但您试图对该元素做什么?您所说的“外部”到底是什么意思php?只需将其分配给一个变量,然后执行一些基本操作,如选择它value@JoshBjelovuk@Marilee外部请更新您的完整代码以明确说明
<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 optionText = $("#winner option:selected").text();
var optionValue = $("#winner option:selected").val();
});
</script>
<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>
<select name="picks" id="winner">
<option value=""></option>
<option value="" selected></option>
</select>