【问题标题】:replace text with select menu用选择菜单替换文本
【发布时间】:2018-10-24 14:05:22
【问题描述】:

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

【问题讨论】:

    标签: jquery ajax function select


    【解决方案1】:

    您将包含您的代码的脚本标记放在 HTML 标记之前...因此,在解析代码时,选择器 select[name="dropdown"]#div2 所针对的元素尚不存在。

    因此,您可以将包含您的代码的脚本标记放在文件末尾,就在&lt;/body&gt; 上方 使用document ready 处理程序包装您的代码,如下所示:

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

    【讨论】:

    • pssst.... OP ask 你取消删除你的answer 以便他可以接受:)
    • 我为您的 ajax 请求添加了错误回调...查看控制台以获取错误消息。这是我能想到的唯一可能的错误。
    猜你喜欢
    • 2010-11-16
    • 2023-03-24
    • 2011-04-11
    • 2016-11-08
    • 2019-02-13
    • 2020-02-27
    • 2012-09-05
    • 2015-03-08
    相关资源
    最近更新 更多