【问题标题】:Jquery change label text with inner inputJquery使用内部输入更改标签文本
【发布时间】:2014-08-18 09:48:10
【问题描述】:

我是 Jquery 的新手。我想在更改输入框时更改标签文本。我有名称为 email 的输入框。

<input type="text" name="email" id="email" />

当输入框更改时,我想将标签文本设置为:将副本发送到我的邮件:mail@example.com

<label for="sendCopy">
<input id="sendCopy" type="checkbox" checked="" name="copy"></input>
    Send copy to my mail
</label>

我有这个 Jquery 代码:

$(function () {
    $("#email").keyup(function () {
        var email = $("#email").val();
        $("label[for='sendCopy']").val('Send copy to my mail: ' + email);
    });
});

但是当keyup功能被触发时,标签被改右,但内部输入被删除。

<label for="sendCopy">
   Send copy to my mail mail@example.com
</label>

希望你能理解我的问题。

【问题讨论】:

  • input 是一个空元素,它没有结束标签。

标签: javascript jquery


【解决方案1】:

您可以将标签的文本包裹在 span 中,以便于选择:

$("#email").keyup(function() {
  $('label[for="sendCopy"] span').text('Send copy to my mail: ' + $(this).val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" name="email" id="email" />

<label for="sendCopy">
  <input id="sendCopy" type="checkbox" checked="" name="copy" />
  <span>Send copy to my mail</span>
</label>

或者,您可以保持 HTML 原样并直接修改 textNode。

$("#email").keyup(function() {
  var textNodes = $('label[for="sendCopy"]').contents().filter(function() {
    return this.nodeType == 3;
  });
  textNodes[textNodes.length - 1].nodeValue = 'Send copy to my mail: ' + $(this).val();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="email" />

<label for="sendCopy">
  <input id="sendCopy" type="checkbox" checked="" name="copy" />
  Send copy to my mail
</label>

【讨论】:

  • 感谢您的帮助。我无法更改表单结构,因为结构是由框架生成的。对于第二个解决方案,我尝试了这个,但只有当我将代码更改为:var tmp = $('label[for="sendCopy"]').contents().filter(function() { return this.nodeType === 3; }).last(); tmp[0].nodeValue = 'Send copy to my mail: ' + $(this).val();
  • @LiborVymětalík 你可以使用$('label[for="sendCopy"]').contents().filter(function() { return this.nodeType == 3; }).last().replaceWith("Send copy to my mail: " + $(this).val());
  • @LiborVymětalík 啊,是的,那是我的代码中的一个错误。我已经为你更新了答案。
  • @RoryMcCrossan 再次感谢您的帮助 :) 现在工作正常
  • 如果我有多个动态输入并且无法处理每个标签怎么办?为什么我不能使用$(this).parent().find('span').text()
【解决方案2】:

只是改变

<label for="sendCopy">
<input id="sendCopy" type="checkbox" checked="" name="copy"></input>
Send copy to my mail
</label>

<input id="sendCopy" type="checkbox" checked="" name="copy"></input>
<label for="sendCopy">
Send copy to my mail
</label>

【讨论】:

  • 我无法更改表单结构,因为它是由框架生成的。框架支持更改表单模板,但在这种情况下,它是不必要的:)
【解决方案3】:

您正在将标签的内容更改为文本,因此其中的输入被删除,输入是值的一部分。

您必须将输入放在标签之外,在它之前。

【讨论】:

  • -1 您并不总是有办法更改 html。你的回答没有回答问题,它应该进入评论。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-04-19
  • 1970-01-01
  • 2012-05-13
  • 1970-01-01
  • 2012-05-08
  • 1970-01-01
  • 2014-10-11
相关资源
最近更新 更多