提问者:小点点

Textarea的内嵌编辑-如何获得ID?


我使用jqInlineEdit在网页上进行内联编辑。 一切正常,只是我不知道如何获取项目的id,我需要该项目将更改保存到数据库(通过Django)。

HTML如下所示:

<div id="remark14756" class="remark" data-cid="14756">
    Sample Text
</div>

这就是JavaScript:

<script src="/static/inline-edit.jquery.js"></script>
<script>

    $(".remark").inlineEdit({
        type: 'textarea',

        onChange: function (e, text, html) {
            // Executes when exiting inline edit mode and a change has been made
            c_id = $(this).attr("data-cid");
            alert("Test: ", c_id)
        }
    });
</script>

显然,$(this)在此上下文中不起作用。 我什么都试过了,找了很多,但我找不到正确的方法。 有人知道答案吗?


共1个答案

匿名用户

inlineEdit文档显示:

onChange(this,text,html)-退出内联编辑模式且已进行更改时执行

使用时,这个会引起很大的误解。

因此,第一个参数实际上是元素。

$(".remark").inlineEdit({
    type: 'textarea',

    onChange: function (elem, text, html) {

       // `this` refers to inlineEdit instance plugin
       // `elem` is the currently edited element

       const c_id = $(elem).attr("data-cid");
       alert(c_id);  // 14756
    }
});

该插件没有以预期的“jQuery插件”方式执行。
通常正确编写的插件应该:

  • 将所有方法绑定到被调用元素,
  • (对于事件方法)第一个参数应该始终引用原始事件。

允许开发人员使用this关键字引用它以获取本机JS元素,或者在公开的公共方法中执行$(this),就像我们期望从本机jQuery方法中执行的那样,并访问事件(即:在使用箭头函数提取CurrentTarget的情况下非常有用,因为this关键字不存在)

$someElem.on('click', function(evt) {
  const $el = $(this); // what we're used to
});

$someElem.on('click', (evt) => {
  const $el = $(evt.currentTarget); // the importance of always passing the Event as first param
});

显然没有在该插件中实现。