javascript - 带有转到网址按钮的条件下拉框?
问题描述
我正在我的网站上设置一个页面,该页面有2 个下拉框,第二个是从第一个下拉框中的选定选项填充的。
我的代码运行完美,但是我无法go
在第二个下拉框中找到按钮来调用URL
要转到的选定值。
如何Find Course
从下拉框 2 中获取用于调用所选选项中的 URL 的按钮?
任何帮助将不胜感激:) 我对 JavaScript 和高级 HTML 非常陌生。
HTML
<div id="myQuestions">
<select id="QuestionOptions">
<option value="Aa">Choose a Faculty</option>
<option value="Ba">Faculty 1</option>
<option value="Ca">Faculty 2</option>
</select>
</div>
<div id="myAnswers">
<div id="Aa" style="display: Aa;">
<div id="F1">
<select id="F1answers">
<option value="A1">Course Selection</option>
</select>
</div>
</div>
<div id="Ba" style="display: none;">
<div id="F2">
<select id="F2answers">
<option value="URL 1 GOES HERE">Course 1</option>
<option value="URL 2 GOES HERE">Course 2</option>
</select>
</div>
</div>
<div id="Ca" style="display: none;">
<div id="F3">
<select id="F3answers">
<option value="URL 3 GOES HERE">Course 3</option>
</select>
</div>
</div>
</div>
<div class="FindCourse">
<a id="CourseGo" href="HOMEPAGE URL"> Find Course </a>
</div>
JS
$(function () {
$('#QuestionOptions').change(function () {
$('#myAnswers > div').hide();
$('#myAnswers').find('#' + $(this).val()).show();
});
});
var sel = document.getElementById('myAnswers');
sel.onchange = function () {
document.getElementById("CourseGo").href = this.value;
}
解决方案
您不应将属性 id用于多个元素,但是此脚本将根据您的逻辑工作:
const $myAnswersDiv = $("#myAnswers > div");
const $courseGo = $("#CourseGo");
const $myAnswers = $("#myAnswers");
$(function() {
$("#QuestionOptions").change(function() {
$myAnswersDiv.hide();
$myAnswers.find("#" + $(this).val()).show();
// targeting (#myAnswers > div > select) without style="display: none"
let $selectVisible = $myAnswersDiv
.not('[style$="display: none;"]')
.find("select");
// setting the current value of select to <a id="CourseGo">
$courseGo.attr("href", $($selectVisible).val());
// listener on the current <select> to set value to <a id="CourseGo">
$selectVisible.change(function() {
$courseGo.attr("href", $(this).val());
});
});
});
推荐阅读
- razor - 如何在剃刀脚本中插入带有 2sxc 的实体?
- c# - C#我无法在html文件中查看图片
- java - Java8 流中的条件排序
- intellij-idea - 强制 IntelliJ 重新运行注释处理器?
- docker - 两个容器之间是否可以直接连接(网卡到网卡)?
- laravel - production.ERROR: Route [appraisal.appraisal_goals.manager_employee_goal_list] 未在 Laravel 中定义
- google-apps-script - 访问 Google Web App 脚本时遇到问题
- javascript - Jest 测试通过但得到一个错误:在渲染组件时序列化从 `getStaticProps` 返回的 `symbol` 时出错。为什么?
- twitter-bootstrap - Bootstrap 不会从 index.html 文件或 aboutme.file 加载,收到错误:“加载资源失败:服务器响应状态为 404 ()”
- javascript - 为什么我们需要在 javascript 类中使用静态方法