如果标签包含特定的文本字符串,我想更改HTML下拉列表的选项。
例如,如果标签包含文本'Object',就像下面那样,那么我想更改下拉选项。
所以
<form id="form-container">
<ul>
<li class="gfield" id="field_302_9"><label class="gfield_label" for="input_302_9">Object<span class="gfield_required">*</span></label></li>
</ul>
<div class="ginput_container ginput_container_select">
<select aria-invalid="false" aria-required="true" class="large gfield_select" id="input_302_9" name="input_9" tabindex="7">
<option value="Option 1">
Option 1
</option>
<option value="Option 2">
Option 2
</option>
<option value="Option 3">
Option 3
</option>
</select>
</div>
</form>
会变成:
<form id="form-container">
<ul>
<li class="gfield" id="field_302_9"><label class="gfield_label" for="input_302_9">Object<span class="gfield_required">*</span></label></li>
</ul>
<div class="ginput_container ginput_container_select">
<select aria-invalid="false" aria-required="true" class="large gfield_select" id="input_302_9" name="input_9" tabindex="7">
<option value="Option 4">
Option 4
</option>
<option value="Option 5">
Option 5
</option>
<option value="Option 6">
Option 6
</option>
</select>
</div>
</form>
使用jQuery怎么可能呢?
答案 0 :(得分:0)
您可以使用jQuery获取标签文本并更改选项输入的HTML。
标签是对象吗?
var labelText = $('.gfield_label').text();
var isObject = /Object/.test(labelText);
根据标签
更改选项if (isObject) {
var newOptions = '<option value="Option 4">'+
'Option 4'+
'</option>'+
'<option value="Option 5">'+
'Option 5'+
'</option>'+
'<option value="Option 6">'+
'Option 6'+
'</option>';
$('.gfield_select').html(newOptions)
}
工作jsbin:http://jsbin.com/sasumivuvi/edit?html,js,console,output
另一方面,我建议不要更改HTML,而是尝试为给定的参数编写HTML。
答案 1 :(得分:0)
由于您对标签究竟如何获得其价值以及该值将如何影响选择标签感到非常模糊,因此这里有一个特定的方法来了解标签的方式。 value可用于相应地填充选择标记。
//here you have a standard js object
//the indexes are the strings from which the label is going to get its text
//and the values for each index will be used to populate the select's options.
//How you populate this object in the first place depends on how you are getting
//the label's possible text and the corresponding options
var obj = {
'labelValue1*':['Option1', 'Option2', 'SneakyOption', 'Option3'],
'labelValue2*':['Option4', 'Option5', 'Option6'],
'labelValue3*':['Option7', 'Option8', 'Option9', 'Option10']
};
//remove all children (options) currently in the select tag
//this is handy in case you intend to update the options in an event fired every time the
//label's text changes
$('#input_302_9').empty();
//jQuery's each function (api.jquery.com/jquery.each/) iterates over
//the options (corresponding to the current text in the label)
//appending each one to the select tag
$.each(obj[$('#field_302_9').text()], function(i, option){
$('#input_302_9').append('<option value="' + option + '">' + option + '</option>');
});
HIH