【问题标题】:How to get the text of a contenteditable span?如何获取内容可编辑范围的文本?
【发布时间】:2017-04-23 15:39:01
【问题描述】:

我的 twig 模板中有一个包含 contenteditable 跨度的表单。我想更改新文本并将其附加到跨度中,因此在提交表单时它包含新文本。

这是我的 html 表单:

<form action="{{ path('change') }}" method="post">
    <span name="profil" class="profil" contenteditable="true">{{ prof.libel }}</span>
    <button name="change" type="submit">
    </button>
</form>

这是我的 jQuery 脚本:

<script>
    $(document).ready(function () {
        $('span.profil').change(function () {
            $text = $(this).text();
            $(this).append(document.createTextNode($text));
        });
    });
</script>

【问题讨论】:

  • 您知道您的 HTML 无效吗?您的打开按钮元素缺少右尖括号
  • 啊好吧,那是因为我在发布这个问题时删除了一些代码。但在我的项目中,我的代码没有遗漏任何东西。

标签: jquery html contenteditable


【解决方案1】:

SPAN 元素没有这样的change 事件。您应该在 BUTTON 的 click 事件或 FORM 的 submit 事件中捕获 span 的文本,例如

$('#theForm').on("submit", function() {
    var text = $('span.profil').text();
    // or  $('span.profil')[0].innerHTML;
});

// or...
$('#theButton').on("click", function() {
    var text = $('span.profil').text();
});

Refdivspan 等实现了 HTMLElement 接口,该接口没有与 change 事件的交互。检查支持处理change event 的元素。

【讨论】:

  • 如果我把 span 改成 div 会起作用吗???因为我看到了很多 div 例子
  • divspan 和其他实现了 HTMLElement 接口,该接口没有与change 事件的交互。检查支持处理 change event 的元素
  • 我认为这在我的情况下行不通,因为我已经动态创建了按钮和跨度元素,所以我如何确定要使用哪个跨度和哪个按钮???
猜你喜欢
  • 2018-03-02
  • 2017-01-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-09
相关资源
最近更新 更多