首页 > 解决方案 > 功能适用于页面加载,但不适用于点击

问题描述

var names = [];
$(document).ready(function(){
	$('#selauth option').each(function(){
		names.push($(this).text());
	});
});

function givemefirst() {
	$('.pmarked').removeClass('pmarked');
	$('.postitle').eq(0).addClass('pmarked');
	givemestuff();
}

givemefirst();

function givemestuff() {
	let obj = $('.pmarked');
	$('.optemp').remove();
	let auth = obj.attr('data-auth');
	if (names.includes(auth)) {
		$('#selauth').val(auth);
	}
	else {
		$('#selauth').append("<option class='optemp'>" + auth + "</option>");
		$('#selauth').val(auth);
	}
}

$(document).on('click', '.postitle', function() {
	$('.pmarked').removeClass('pmarked');
	$(this).addClass('pmarked');
	givemestuff();
});
.postitle{
cursor:pointer;
}

.pmarked{
background:gold;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='postitle' data-auth='earth'>lorem ipsum</div>
<div class='postitle' data-auth='moon'>lorem ipsum</div>
<div class='postitle' data-auth='sun'>lorem ipsum</div>
<br>
<select id='selauth'>
<option>moon</option>
<option>sun</option>
</select>

在页面加载一切正常。
option-earth添加到selauth并自动选择它。

单击下一步postitle也有效 -option-earth已删除...

但是先再次点击postitle-selauth是空白的,即没有选择选项,即option-earth没有添加!

怎么了?

标签: javascriptjqueryhtmlcss

解决方案


您只需将其更改为:

演示:https ://codepen.io/creativedev/pen/RJYapd

var names = [];
$(document).ready(function(){
    $('#selauth option').each(function(){
        names.push($(this).text());
    });
});

function givemefirst() {
    $('.pmarked').removeClass('pmarked');
    $('.postitle').eq(0).addClass('pmarked');
    givemestuff();
}

givemefirst();

function givemestuff() {
    let obj = $('.pmarked');
  $('.optemp').remove();
    let auth = obj.attr('data-auth');  
    if ($("#selauth option[value='"+auth+"']").length > 0) {
        $('#selauth').val(auth);
    }
    else {
        $('#selauth').append("<option class='optemp' value='"+auth+"'>" + auth + "</option>");
        $('#selauth').val(auth);
    }
}

$(document).on('click', '.postitle', function() {
    $('.pmarked').removeClass('pmarked');
    $(this).addClass('pmarked');
    givemestuff();
});

推荐阅读