javascript - 功能适用于页面加载,但不适用于点击
问题描述
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
没有添加!
怎么了?
解决方案
您只需将其更改为:
演示: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();
});
推荐阅读
- javascript - 为什么 React 钩子在 React 文档中使用 const?
- c# - Caliburn Micro 重新加载事件数据
- javascript - Ajax 请求有时会导致“XHR 加载失败:POST”错误
- sql - Charts.js 的 Laravel 查询构建器
- javascript - Cheerio 不工作。我究竟做错了什么?
- python - Python 脚本不会停止运行
- python - 3d numpy 数组中的特定排序类型
- javascript - 函数 addNewDriver() 未定义
- freemarker - 如何获取查询字符串的值?
- sql - 用于报告的 SQL 查询