将文本返回到默认状态 (jQuery)



我试图在我的文档中收集文本字段并将其替换为不同的文本(语言)。这很好,但我无法在不重新加载页面的情况下将其退回。

首先,我希望替换的所有文本字段都具有名为 lang="en" 的属性。

因此,我使用 jQuery .each()函数将它们全部收集到一个数组中,执行以下操作:

$(document).ready(function() {
   $("[lang=en]").each(function(){
   var textArray = $(this).text();
   });
});

而变量 textArray 包含要替换为另一个变量的必需文本字段的集合。例:

var replaceText = textArray.replace("Hello", "Hi").replace("Good afternoon!", "Hi!");

在每个功能中,我可以$(this).text(replaceText)应用替换的文本,但我希望通过按钮单击(button1)来完成,而另一个按钮(button2)会将其更改回来。

按钮内部单击事件(在每个循环函数内)$["lang=en"].text(replaceText);没有正确的效果。

<input type="button" id="convert" value="Convert"/>
<input type="button" id="convert-back" value="Convert Back"/>

#convert将转换具有lang=en属性的所有输入文件中的文本。 #convert-back按钮将执行相反的操作。让我知道它是否适合您


$(document).ready(function () {
    $("#convert").click(function () {
        $("input:lang(en)").each(function () {
            var textArray = $(this).val();
            var replaceText = textArray.replace("Hello", "Hi").replace("Good afternoon!", "Hi!");
            $(this).val(replaceText)
        });
    });
    $("#convert-back").click(function () {
        $("input:lang(en)").each(function () {
            var textArray = $(this).val();
            var replaceText = textArray.replace("Hi", "Hello").replace("Hi!", "Good afternoon!");
            $(this).val(replaceText)
        });
    });
});

编辑

网页部件

<input type="text" lang="en" value="Hello" alt="Hello, stack"/>
<input type="text" lang="en" value="Hello" alt="Hello, over"/>
<input type="text" lang="en" value="Hello" alt="Hello, flow"/>
<input type="text" lang="en" value="Hello" alt="Hello, stack"/>
<input type="text" lang="en" value="Hello" alt="Hello, over"/>
<input type="button" id="convert" value="Convert"/>

Jquery 部分

$(document).ready(function () {
    $("#convert").click(function () {
        $("input:lang(en)").each(function () {
            var textArray = $(this).val();
            var newArray = $(this).attr("alt");
            $(this).val(newArray);
            $(this).attr("alt", textArray);
        });
        if ($(this).val() == "Convert") { $(this).val("Convert back"); } 
        else { $(this).val("Convert"); }
    });
});

将旧值存储到输入框alt标签中以再次替换。让我知道它是否对您有帮助。

最新更新