如何在div id中替换div类文本?

时间:2014-04-18 19:34:28

标签: jquery class html replace

我在squarespace网站上有以下div:

<div id="text-yui_3_10_1_1_1397493196442_28869" class="form-item field text required error">
<div class="field-error">Subject is required.</div>

<div id="number-yui_3_10_1_1_1397494940010_32253" class="form-item field number required error">
<div class="field-error">Phone is required.</div>

我想用jquery更改“field-error”的文本(“Subject is required”/“Phone is required”)

编辑:抱歉,看来上面的所有代码只有在按下“提交”按钮时才会显示。

按钮的代码如下:

<input class="button sqs-system-button sqs-editable-button" type="submit" value="Submit">

是否需要将替换代码与按钮操作相关联?

edit2:好的,我找到了提交按钮的表单代码:

<form onsubmit="return (function(form) { Y.use ('squarespace-form-submit', 'node', function (Y) { (new Y.Squarespace.FormSubmit({ formNode: Y.Node(form) })).submit('534c11ade4b0c1a4ea57934b', '53488d92e4b0f26be11d5d68') }); return false;})(this)" method="POST" action="website_link" autocomplete="on">

谢谢!

1 个答案:

答案 0 :(得分:0)

我必须猜测你的意思,但我认为考虑到你展示的DOM,这是一个非常好的猜测。我想你正在尝试改变多个文本并且它们正在合并,因为你得到的.field-error文本包含多个元素。你必须单独做这些,尝试这样的事情:

JSFiddle

$(".field-error").each( function() {
    $(this).text($(this).text().replace("required", "optional"));
});

这将通过选择器上的每个匹配(.field-error)并单独替换它们。如果您执行$(".field-error").text($(".field-error").text().replace("required", "optional"));之类的操作,则最终会出现合并文本,因为每个.field-error都会包含所有.field-error中的文字。


看到您的更新,看起来您的DOM也是错误的。试试这个:

JSFiddle

HTML:

<div id="text-yui_3_10_1_1_1397493196442_28869" class="form-item field text required error">
<div class="field-error">Subject is required.</div>
</div>

<div id="number-yui_3_10_1_1_1397494940010_32253" class="form-item field number required error">
<div class="field-error">Phone is required.</div>
</div>

CODE:

$fe = $("#text-yui_3_10_1_1_1397493196442_28869 .field-error");
$fe.text($fe.text().replace("Subject is required.", "test"));

使用最新信息...试试这个:

function replacementSubmitFunction() {
    return (function (form) {
        Y.use('squarespace-form-submit', 'node', function (Y) {
            (new Y.Squarespace.FormSubmit({
                formNode: Y.Node(form)
            })).submit('534c11ade4b0c1a4ea57934b', '53488d92e4b0f26be11d5d68')
        });
        $(".field-error").each(function () {
            $(this).text($(this).text().replace("required", "optional"));
        });
        return false;
    })(this)
}
$("form").get(0).onsubmit = replacementSubmitFunction;