我正在向选择框下拉列表和新字体列表中添加自定义字体名称。
随着添加,需要提供删除字体以及。
如果我从列表中删除字体A (这是工作的),同样的字体也应该从下拉列表中删除(不起作用)。
代码低于
$(document).on('click', '#addFont', function(){
var _font_name = jQuery('#fontName').val();
var _font_name_short = _font_name.replace(/\s+/g, '-').toLowerCase();
jQuery('select#fonts option').removeAttr('selected');
jQuery('select#fonts').prepend('<option value="'+_font_name+'" custom-font="'+_font_name_short+'" selected>'+_font_name+'</option>');
jQuery('ul#newFonts').prepend('<li custom-font="'+_font_name_short+'">'+_font_name+' <a href="javascript:;" class="remove-font">Remove</a></li>');
jQuery('#fontName').val('');
})
$(document).on('click', '.remove-font', function(){
var selectedFont = jQuery(this).closest('li').attr('custom-font');
var ddFont = $("select#fonts option").attr('custom-font')
jQuery(this).closest('li').remove();
if (selectedFont == ddFont){
jQuery(ddFont).remove();
}
})div{margin-top:15px;}
a{margin-left:5px;}<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<select id="fonts">
<option value="arial">Arial</option>
<option value="verdana">Verdana</option>
</select>
<input id="fontName" type="text" placeholder="Font name">
<button type="submit" id="addFont">Add font</button>
<div>
<b>New fonts</b>
<ul id="newFonts"></ul>
</div>
发布于 2021-02-10 09:50:07
可以使用$("select#fonts option[value='"+selectedFont+"']").remove();从选择的字体中删除字体。
Demo
$(document).on('click', '#addFont', function() {
var _font_name = jQuery('#fontName').val();
var _font_name_short = _font_name.replace(/\s+/g, '-').toLowerCase();
jQuery('select#fonts option').removeAttr('selected');
jQuery('select#fonts').prepend('<option value="' + _font_name + '" custom-font="' + _font_name_short + '" selected>' + _font_name + '</option>');
jQuery('ul#newFonts').prepend('<li custom-font="' + _font_name_short + '">' + _font_name + ' <a href="javascript:;" class="remove-font">Remove</a></li>');
jQuery('#fontName').val('');
})
$(document).on('click', '.remove-font', function() {
var selectedFont = jQuery(this).closest('li').attr('custom-font');
$("select#fonts option[value='"+selectedFont+"']").remove();
jQuery(this).closest('li').remove();
})div {
margin-top: 15px;
}
a {
margin-left: 5px;
}<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<select id="fonts">
<option value="arial">Arial</option>
<option value="verdana">Verdana</option>
</select>
<input id="fontName" type="text" placeholder="Font name">
<button type="submit" id="addFont">Add font</button>
<div>
<b>New fonts</b>
<ul id="newFonts"></ul>
</div>
https://stackoverflow.com/questions/66134464
复制相似问题