首页 > 解决方案 > 用选择菜单替换文本

问题描述

在 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>

标签: jqueryajaxfunctionselect

解决方案


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>

推荐阅读