我在文章底部设计了一个脚注,以说明后续状态。

<article class="col-md-12">
</article>
<div class="col-md-12 footnote">
    <a href="{% url 'article:footnote_add'%}">add a footnote</a>
</div>


单击后隐藏“添加脚注”链接,并提示我设置了autofocus其中textarea的“脚注表格”。 “ autofucus”正常工作。

$('.footnote-link a').on('click', function (e) {
    e.preventDefault();
    ...
    var $footnoteForm = $(`
<form class="article-footnote-form footnote-form" style="margin-top:10px" >
<div class="form-group row">
    <div class="col-md-9">
        <textarea class="form-control" name="footnote" rows="3" autofocus></textarea>
    </div>
    <div class="col-md-3">
        <button class="btn btn-primary" type="submit" id="articleFootnoteBtn">Add Annotation</button>
    </div>
</div>
</form>`);
     $articleFootnoteLink.parent().hide();
     $articleFootnoteLink.parent().after($footnoteForm);


表单使用Ajax提交到服务器,然后我通过以下方式清除了表单

$footnotesTop.find(".footnote-form").html("")。现在,页面显示文章和新添加的脚注。

但是,如果我再次单击“添加脚注”,它将无法像第一次一样自动获得焦点,直到刷新页面才能单击。

在第二次单击事件期间如何获得表单焦点。

最佳答案

您需要使用委托的eventHandler。 js代码$('.footnote-link a').on('click', function (e) {仅应用于页面加载时jQuery使用该选择器找到的元素。

尝试$( document ).on('click', '.footnote-link a', function (e) {。您可以使用更严格的选择器而不是文档-看来.footnote会根据我所看到的工作。

jQuery delegated events tutorial

10-08 13:02