当用户选择下拉选项时,代码(如下)工作正常,但第一个选项由php根据以前的页面填充。如何在页面加载时获取onchange的onchange事件,获取php附加值并对其进行操作?
<?php
$value = $_GET["value"];
if (!$value){
$value = 'Y';
}
?>
<html>
<head>
<style>
.inv {
display: none;
}
</style>
<script>
function jb(){
document.getElementById("target").value = "Y";
document.getElementById("target").onchange();
}
window.onload = jb;
</script>
</head>
<body>
See more? 
<select name='see_more' id='target'>
<option value='<?php echo $value; ?>'><?php echo $value; ?></option>
<option value='Y'>Y</option>
<option value='N'>N</option>
</select>
<div id="Y" class='inv'>
Additional content goes here
</div>
<script>
document
.getElementById('target')
.addEventListener('change', function () {
'use strict';
var vis = document.querySelector('.vis'),
target = document.getElementById(this.value);
if (vis !== null) {
vis.className = 'inv';
}
if (target !== null ) {
target.className = 'vis';
}
});
</script>
</body>
</html>
答案 0 :(得分:1)
我设法使用php找到了解决方案:
<?php
$value = $_GET["value"];
if (!$value){
$value = 'Y';
}
?>
<html>
<head>
<style>
.inv {
display: none;
}
</style>
</head>
<body>
See more? 
<select name='see_more' id='target'>
<option value='<?php echo $value; ?>'><?php echo $value; ?></option>
<option value='Y'>Y</option>
<option value='N'>N</option>
</select>
<?php
if ($value == 'Y'){
echo "<!--";
}
?>
<div id="Y" class='inv'>
<?php
if ($value == 'Y'){
echo "-->";
}
?>
<?php
if ($value == 'N'){
echo "<!--";
}
?>
<div id="Y" class='vis'>
<?php
if ($value == 'N'){
echo "-->";
}
?>
<br>
Additional content goes here
</div>
<script>
document
.getElementById('target')
.addEventListener('change', function () {
'use strict';
var vis = document.querySelector('.vis'),
target = document.getElementById(this.value);
if (vis !== null) {
vis.className = 'inv';
}
if (target !== null ) {
target.className = 'vis';
}
});
</script>
</body>
</html>
答案 1 :(得分:0)
如果您使用的是jQuery,则可以执行$('#target').change();
。所以:
$(document).ready(function () {
$('#target').change();
});