javascript - 我是否遭受了过多的递归? JQuery - 在某些情况下必须点击按钮两次

标签 javascript jquery events recursion click

我正在使用他们的纯文本 API 为链接锁定网站制作一个多链接锁(ot:使用 YQL 来完成这个但还没有那么远)

它使用 localStorage 来保存用户的 API key 。但我遇到了问题。添加 key 并且用户点击保存后,将显示链接添加表单。从这里开始,当单击“如果此键不正确,请单击此处。”时,在用户再次单击该链接之前什么都不会发生。

“添加”按钮也是如此。必须点击两次。此外,如果单击添加按钮,“如果此 key 不正确,请单击此处”。链接按预期运行。最主要的是,页面上的任何可点击元素都必须先被点击一次,然后相关的可点击元素才会按预期运行。

我认为它可能与默认事件操作有关,所以我尝试使用 preventDefault() 来查看它是否修复了任何问题,但无济于事。我真的很想得到更有知识的人的帮助。

我已经把演示放到网上了:API Tools ,GitHub repo 可以在这里找到:GitHub

在键表中输入任意字符串值进行测试。另外,首先单击“添加”按钮。请注意页面如何导航到“/?”?那会和它有什么关系吗?请看下面的代码:

<!DOCTYPE html>

<html lang="en">
<head>
    <meta charset="utf-8" />
    <title>Shrink Once API Tools</title>
    <link rel="stylesheet" type="text/css" href="css/bootstrap.css"></link>
    <link rel="stylesheet" type="text/css" href="css/bootstrap-responsive.css"></link>
</head>
<body>
    <div class="container-fluid">
        <div class="row-fluid">
            <div class="span12">
                <h1 class="head-title">Shrink Once API Tools</h1>
            </div>
        </div>
        <div class="row-fluid">
            <div class="span12">
                <div class="flashAlert">

                </div>
            </div>
        </div>
        <div class="row-fluid">
            <div class="span12">
                <div class="mainFormContent">

                </div>
            </div>
        </div>
    </div>

    <!-- Include JavaScript at the very bottom for faster page loads -->
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
    <!--
    Fall back on local JQuery if Google CDN version is unavailable.
    (Since most sites link the Google CDN version, it is more likely
    to already be cached by the user's browser).
    -->
    <script>window.jQuery || document.write('<script src="js/vendor/jquery-1.8.2.min.js"><\/script>')</script>
    <!-- end Fallback -->
    <script src="js/bootstrap.js"></script>
    <script>
        $(function () {
            var apiKeyForm = '<form class="apiKeyForm">'
                           + '<legend>Enter your API Key</legend>'
                           + '<input type="text" id="apiKey" class="span12" placeholder="e.g. ab12c34d5678efgh90123i45678j90k1">'
                           + '<span class="help-block">You can find your access key <a href="https://shrinkonce.com/index.php?menu=usercp#tools" target="blank">here.</a></span>'
                           + '<button id="saveAPIKey" class="btn btn-info btn-large btn-block">Save</button>'
                           + '</form>';

            var apiLinkForm = '<form class="apiLinkForm">'
                            + '<legend>Add a link or two... or more.</legend>'
                            + '<button id="add" class="btn btn-large">Add</button>'
                            + '<button id="remove" class="btn btn-large">Remove</button>'
                            + '<button id="reset" class="btn btn-large">Reset</button>'
                            + '<button class="btn btn-info btn-large">Submit</button>'
                            + '<hr />'
                            + '<div id="linkForm">'
                            + '</div>'
                            + '</form>';

            if (localStorage.length > 0) {
                $('<div class="alert alert-success">Your API token is <b>' + localStorage.getItem('apiKey') + '</b>. If this key is incorrect, click <a href="" class="resetLocalStorage">here</a>.</div>').appendTo('.flashAlert').fadeIn('slow');
                $(apiLinkForm).fadeIn('slow').appendTo('.mainFormContent');
            }
            else {
                $('<div class="alert alert-error">You have not yet entered your API token. Add it below, and it will be persisted in memory.</div>').appendTo('.flashAlert').fadeIn('slow');
                $(apiKeyForm).fadeIn('slow').appendTo('.mainFormContent');
            }

            var i = $('#linkForm input').size() + 1;
            $('#add').click(function (e) {
                e.preventDefault();
                $('<input type="text" id="inputLink' + i + '" class="shrinklink span12" placeholder="http://google.com">').fadeIn('slow').appendTo('#linkForm');
                i++;
                return false;
            });
            $('#remove').click(function (e) {
                e.preventDefault();
                if (i > 1) {
                    $('.shrinklink:last').fadeOut('normal', function () { $(this).remove(); });
                    i--;
                }
                return false;
            });
            $('#reset').click(function (e) {
                e.preventDefault();
                while (i > 1) {
                    $('.shrinklink:last').remove();
                    i--;
                }
                return false;
            });
            $('#saveAPIKey').click(function (e) {
                e.preventDefault();
                if ($('#apiKey').val().length > 0) {
                    localStorage.setItem('apiKey', $('#apiKey').val());
                    $('.alert').replaceWith('<div class="alert alert-success">Your API token is <b>' + localStorage.getItem('apiKey') + '</b>. If this key is incorrect, click <a href="" class="resetLocalStorage">here</a>.</div>');
                    $('.apiKeyForm').replaceWith(apiLinkForm);
                }
                else {
                    $('.alert').replaceWith('<div class="alert">You did not enter your API key! Please enter it below.</div>');
                }
                return false;
            });
            $('.resetLocalStorage').click(function (e) {
                e.preventDefault();
                localStorage.clear();
                location.reload();
                return false;
            });
        });
    </script>
</body>

最佳答案

问题是,您正在为当时存在于 DOM 中的项目绑定(bind)(通过使用 .click 方法)事件处理程序。这些不适用于稍后添加的节点,这里就是这种情况(例如,您要附加带有“.mainFormContent”链接的消息)。

最简单的解决方法是将 .click 的用法替换为 .on 方法,例如:

$(document).on('click', '.resetLocalStorage', function (e) {
    e.preventDefault();
    localStorage.clear();
    location.reload();
    return false;
});

请记住,这只是一个快速修复。至于架构方法,它不是最好的,但这是一个完全不同的问题。

关于javascript - 我是否遭受了过多的递归? JQuery - 在某些情况下必须点击按钮两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13066338/

相关文章:

javascript - Angular,在 $last 上嵌套重复触发事件

javascript - 如何使用 Javascript 或 jQuery 表单编辑 .txt 文件

javascript - jquery 检查 img 是否在 div 中

jquery - 为什么程序无法读取文件 json?

kotlin - Corda事件调度中的可调度状态

php - Symfony 事件订阅者对调度没有反应

javascript - 在 React Native 项目中,为什么导入中的顶级目录被称为 'app' ?

javascript - 我们如何在不转换代码的情况下在现代网络浏览器中使用 es6 模块

javascript - 通过 JS 函数发布输入字段值

excel - Set ForeColor 不会在 Exit 事件中执行