我有以下代码(它是jquery,但使用php添加动态变量):
jQuery(document).ready(function($){
var arr = [ 'select', 'checkbox', 'radio' ];
var thisForm = 'select#widget-layers-widget-form_builder-<?php echo $this->number; ?>-form_builders-<?php echo esc_attr( $item_guid ); ?>-input_type';
if ($('select#widget-layers-widget-form_builder-<?php echo $this->number; ?>-form_builders-<?php echo esc_attr( $item_guid ); ?>-input_type option:selected').val() == 'select'){
$('#select-options-<?php echo esc_attr( $item_guid ); ?>').show();
}else{
$('#select-options-<?php echo esc_attr( $item_guid ); ?>').hide();
}
$(thisForm).change(function(){
if ($('select#widget-layers-widget-form_builder-<?php echo $this->number; ?>-form_builders-<?php echo esc_attr( $item_guid ); ?>-input_type option:selected').val() == 'select'){
$('#select-options-<?php echo esc_attr( $item_guid ); ?>').show();
}else{
$('#select-options-<?php echo esc_attr( $item_guid ); ?>').hide();
}
});
});
这样做的目的是检查下拉菜单的值并根据选择显示/隐藏元素。目前,如果下拉选择 == "选择",则代码旨在工作,但是,我想在这里添加一个结果数组,本质上,如果下拉值等于"选择"、"复选框"或"单选"。
如何通过编写数组并根据它检查值来实现这一点?
首先,不要在 init 中重复你的代码,然后在更改中重复你的代码(至少,它看起来是重复的,很难用所有的 php tbh 来分辨)。
接下来,将值与比较分开,这也使查看正在发生的事情变得更加容易:
var arr = [ 'select', 'checkbox', 'radio' ];
var thisForm = 'select#widget-layers-widget-form_builder-<?php echo $this->number; ?>-form_builders-<?php echo esc_attr( $item_guid ); ?>-input_type';
function showHideSelect() {
var val = $(thisFrom + ' option:selected').val();
var select = $('#select-options-<?php echo esc_attr( $item_guid ); ?>')
if (val == 'select'){
select.show();
} else {
select.hide();
}
}
jQuery(document).ready(function($) {
showHideSelect();
$(thisForm).change(function(){
showHideSelect();
});
});
现在有问题的部分只是if (val == 'select')
,您可以将其更改为:
if (arr.indexOf(val) >= 0)
select.show();
else
select.hide();