jquery - 用选择菜单替换文本
问题描述
在 jquery 的帮助下,我创建了一个脚本,用外部 .txt 文档中的文本替换 html 页面中的文本。但不知何故它不起作用:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
<script>
$('select[name="dropdown"]').change(function(){
if ($(this).val() == "2"){
$.ajax({url: "demo_test2.txt", success: function(result){
$("#div2").html(result);
}});
});
</script>
</head>
<body>
<div id="div2"><h2>John</h2></div>
<select name="dropdown">
<option id="button" value="1">English</option>
<option id="button2" value="2">Dutch</option>
</select>
</body>
</html>
解决方案
select[name="dropdown"]
您将包含您的代码的脚本标记放在 HTML 标记之前...因此,选择器所针对的元素在#div2
解析代码时还不存在。
因此,您可以将包含您的代码的脚本标签放在文件的末尾,就在上面,</body>
或者使用这样的文档就绪处理程序包装您的代码:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
<script>
$(document).ready(function(){ // Add this
$('select[name="dropdown"]').change(function(){
if ($(this).val() == "2"){
$.ajax({
url: "demo_test2.txt",
success: function(result){
$("#div2").html(result);
},
error: function(request,status,error){
console.log(error);
}
});
});
}); // And this
</script>
</head>
<body>
<div id="div2"><h2>John</h2></div>
<select name="dropdown">
<option id="button" value="1">English</option>
<option id="button2" value="2">Dutch</option>
</select>
</body>
</html>
推荐阅读
- session - 嵌入 iframe 时,应用会发送另一个会话 cookie
- python - IndexError:列表索引超出范围python(烧瓶)
- logging - Ruby on rails:Ruby on rails 6 中的默认日志格式是什么
- python - 动态更改帧 tkinter
- javascript - 单击时触发两次 HTML 按钮
- javascript - 为什么删除菜单手机不起作用?
- bash - 文件中的 Bash Hex 到 Dec IP 转换
- javascript - 对象数组获得具有唯一 ID 的总数
- docker - 访问 Docker 内的 .NET Core 控制台应用程序生成的日志文件
- c++ - 在不使用 cv::warpAffine(...) 的情况下向所有方向移动 cv::Mat