当用户选择下拉选项时,代码(下面)运行良好,但第一个选项是由php根据以前的页面填充的。当页面加载时,我如何让select的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>
我设法使用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>
如果您使用的是jQuery,您可以只执行$('#target').change();
。因此:
$(document).ready(function () {
$('#target').change();
});