在所有标签中查找单词,并在jQuery中替换它

问题描述 投票:0回答:1

我有多个带有标签的输入字段,标签以单词“ Shop”开头,即店铺信:店铺编号:店铺信函文件:我有一个下拉菜单,其中有两个选项“商店”和“商店”。我想从下拉菜单中选择“存储”时更改为“存储”。

这是我到目前为止所做的;

<form action="" id="form_type">
    <label for="type">Choose a type:</label>
    <select id="type">
        <option value="shop">Shop</option>
        <option value="store">Store</option>
    </select><br><br>
    <label for="Shop_Letter">Shop Letter :</label>
    <input type="text" id="Shop_Letter" name="Shop_Letter"><br><br>
    <label for="Shop_Letter_No">Shop Letter No :</label>
    <input type="text" id="Shop_Letter_No" name="Shop_Letter_No"><br><br>
    <label for="Shop_Letter_File">Shop Letter File :</label>
    <input type="text" id="Shop_Letter_File" name="Shop_Letter_File"><br><br>
</form>


$("#type").on('change', function(){
        var shop_letter = $("label[for='Shop_Letter']").html(); //Get the text
        var shop_letter_no = $("label[for='Shop_Letter_No']").html(); //Get the text
        if (this.value == 'store'){
            $("label[for='Shop_Letter']").html(shop_letter.replace("Shop", "Store"));
            $("label[for='Shop_Letter_No']").html(shop_letter_no.replace("Shop", "Store"));
        }else{
            $("label[for='Shop_Letter']").html(shop_letter.replace("Store", "Shop"));
            $("label[for='Shop_Letter_No']").html(shop_letter_no.replace("Store", "Shop"));
        }
    });

当我手动选择标签并分配var,但是我想选择所有标签并使用适当的方法对其进行更改时,它确实以这种方式工作。我似乎无法自己解决这个问题。谢谢

javascript html jquery jquery-ui xhtml
1个回答
0
投票

您应该尝试将代码放入$( document ).ready()函数中。

jquery documentation

在文档“准备就绪”之前,无法安全地操纵页面。 jQuery为您检测到这种就绪状态。 $(document).ready()内包含的代码仅在页面Document Object Model(DOM)准备好执行JavaScript代码后才能运行。一旦整个页面(图像或iframe)(不仅是DOM)准备就绪,$(window).on(“ load”,function(){...})中包含的代码将运行。

编辑代码:

$( document ).ready(function() {
    $("#type").on('change', function(){
        var shop_letter = $("label[for='Shop_Letter']").html(); //Get the text
        var shop_letter_no = $("label[for='Shop_Letter_No']").html(); //Get the text
        if (this.value == 'store'){
            $("label[for='Shop_Letter']").html(shop_letter.replace("Shop", "Store"));
            $("label[for='Shop_Letter_No']").html(shop_letter_no.replace("Shop", "Store"));
        }else{
            $("label[for='Shop_Letter']").html(shop_letter.replace("Store", "Shop"));
            $("label[for='Shop_Letter_No']").html(shop_letter_no.replace("Store", "Shop"));
        }
    });
});

快乐编码!

© www.soinside.com 2019 - 2024. All rights reserved.