jquery事件在单击时触发两次

时间:2017-07-14 12:33:42

标签: javascript jquery onclick html-table

我正在使用一个Web应用程序,我正在重新排序HTML表行,并且看到何时单击带有类的项目。事件发生两次,但我不知道如何。

如果有人能够让我知道如何阻止这种行为,我将不胜感激,因为这将创建一个AJAX调用并将数组传递回后面的代码,但我只需要并且希望它能够触发一次。



bootstrap/
├── css/
│   ├── bootstrap.css
│   ├── bootstrap.css.map
│   ├── bootstrap.min.css
│   ├── bootstrap.min.css.map
│   ├── bootstrap-theme.css
│   ├── bootstrap-theme.css.map
│   ├── bootstrap-theme.min.css
│   └── bootstrap-theme.min.css.map
├── js/
│   ├── bootstrap.js
│   └── bootstrap.min.js
└── fonts/
    ├── glyphicons-halflings-regular.eot
    ├── glyphicons-halflings-regular.svg
    ├── glyphicons-halflings-regular.ttf
    ├── glyphicons-halflings-regular.woff
    └── glyphicons-halflings-regular.woff2

@XmlRootElement(name = "config")
public class Cfg {
    public Cfg() {
    }

    @XmlElementWrapper(name = "avoidanceList")
    @XmlElement(name = "avoid", required = false)
    private List<String> avoidanceList;

    @XmlElementWrapper(name = "ignoreList")
    @XmlElement(name = "ignore", required = false)
    private List<String> ignoreList;

    @XmlElement(name = "mailConfig")
    private MailConfig mailConfig;


    public List<String> getAvoidanceList() {
        return avoidanceList;
    }

    public List<String> getIgnoreList() {
        return ignoreList;
    }

    public MailConfig getMailConfig() {
        return mailConfig;
    }
}

public class MailConfig {
    @XmlElementWrapper(name = "toList")
    @XmlElement(name = "to")
    private List<String> toList;

    @XmlElement(name = "from", required = false)
    private String from;

    public MailConfig() {
    }

    public String getFrom() {
        return from;
    }

    public List<String> getToList() {
        return toList;
    }
}
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:4)

您的症状与您的代码不符,但症状的三个最可能的原因是(我倾向于#3):

  1. 您有.up.down.bottom.top元素 .up,{ {1}},.down.bottom元素。所以,自从.top传播(并且jQuery在执行事件委托时忠实地复制它)时,它会触发最内层匹配,也适用于最外层匹配。

    如果是这样,请直接针对相关元素定位处理程序。

  2. 您运行了两次代码,因此设置了两个处理程序,每个处理程序都在触发。

    如果是这样,呃,不要这样做。 : - )

  3. 您的click位于另一个table内,因此table与其中的$("table")匹配,并且因为click传播(这次是DOM级别),你得到两个表的答复。

    如果是这样,请仅定位您希望这些处理程序连接的表。

  4. 由于您的代码没有复制它,这里是#1的简化示例:

    $("table").on("click", ".up, .down", function() {
      console.log(this.className + " clicked");
    });
    <table>
      <tbody>
        <tr class="up">
          <td class="down">Click me</td>
        </tr>
      </tbody>
    </table>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

    ......和#2:

    $(document).ready(setup);
    $(window).load(setup);
    function setup() {
      $("table").on("click", ".up, .down", function() {
        console.log(this.className + " clicked");
      });
    }
    <table>
      <tbody>
        <tr>
          <td class="down">Click me</td>
        </tr>
      </tbody>
    </table>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

    ......和#3:

    $("table").on("click", ".up, .down", function() {
      console.log(this.className + " clicked");
    });
    <table>
      <tbody>
        <tr>
          <td>
            <table>
              <tbody>
                <tr>
                  <td class="down">Click me</td>
                </tr>
            </tbody>
          </table>
        </td>
      </tr>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

答案 1 :(得分:1)

1)当您为多次点击事件分配相同的处理程序时,可能会发生这种情况。我建议,请仔细检查分配处理程序的行。我猜它被多次调用。一个解决方案可能是先取消绑定然后绑定调用,如下所示:

{
"documents": [{
        "documentId": "1136641236",
        "uri": null,
        "remoteUrl": null,
        "name": "ABC Merchant Agreement",
        "password": null,
        "transformPdfFields": null,
        "fileExtension": null,
        "matchBoxes": null,
        "order": null,
        "pages": null,
        "documentFields": null,
        "encryptedWithKeyManager": null,
        "documentBase64": "documentBase64",
        "applyAnchorTabs": null
    }
],
"recipients": {
    "signers": [{
            "signatureInfo": null,
            "defaultRecipient": null,
            "tabs": {
                "signHereTabs": [{
                        "name": null,
                        "tabLabel": null,
                        "scaleValue": null,
                        "optional": null,
                        "documentId": "1136641236",
                        "recipientId": "2044556663",
                        "pageNumber": "1",
                        "xPosition": null,
                        "yPosition": null,
                        "anchorString": "SIGNATUREOWNER1",
                        "anchorXOffset": null,
                        "anchorYOffset": null,
                        "anchorUnits": null,
                        "anchorIgnoreIfNotPresent": null,
                        "anchorCaseSensitive": "True",
                        "anchorMatchWholeWord": "True",
                        "anchorHorizontalAlignment": null,
                        "tabId": null,
                        "templateLocked": null,
                        "templateRequired": null,
                        "conditionalParentLabel": null,
                        "conditionalParentValue": null,
                        "customTabId": null,
                        "mergeField": null,
                        "status": null,
                        "errorDetails": null
                    }
                ],
                "initialHereTabs": null,
                "signerAttachmentTabs": null,
                "approveTabs": null,
                "declineTabs": null,
                "fullNameTabs": null,
                "dateSignedTabs": null,
                "envelopeIdTabs": null,
                "companyTabs": null,
                "titleTabs": null,
                "textTabs": [{
                        "height": null,
                        "isPaymentAmount": null,
                        "formula": null,
                        "validationPattern": null,
                        "validationMessage": null,
                        "shared": null,
                        "requireInitialOnSharedChange": null,
                        "senderRequired": null,
                        "requireAll": null,
                        "name": "TextTab",
                        "value": null,
                        "originalValue": null,
                        "width": null,
                        "required": "true",
                        "locked": "false",
                        "concealValueOnDocument": null,
                        "disableAutoSize": null,
                        "maxLength": null,
                        "tabLabel": "gjk",
                        "font": null,
                        "bold": null,
                        "italic": null,
                        "underline": null,
                        "fontColor": null,
                        "fontSize": "Size12",
                        "documentId": "1136641236",
                        "recipientId": "2044556663",
                        "pageNumber": "1",
                        "xPosition": null,
                        "yPosition": null,
                        "anchorString": "TEXTTABPLACEHOLDER",
                        "anchorXOffset": null,
                        "anchorYOffset": null,
                        "anchorUnits": null,
                        "anchorIgnoreIfNotPresent": null,
                        "anchorCaseSensitive": "True",
                        "anchorMatchWholeWord": "True",
                        "anchorHorizontalAlignment": null,
                        "tabId": null,
                        "templateLocked": null,
                        "templateRequired": null,
                        "conditionalParentLabel": null,
                        "conditionalParentValue": null,
                        "customTabId": null,
                        "mergeField": null,
                        "status": null,
                        "errorDetails": null
                    }
                ],
                "numberTabs": null,
                "ssnTabs": null,
                "dateTabs": null,
                "zipTabs": null,
                "emailTabs": null,
                "noteTabs": null,
                "checkboxTabs": null,
                "radioGroupTabs": null,
                "listTabs": null,
                "firstNameTabs": null,
                "lastNameTabs": null,
                "emailAddressTabs": null,
                "formulaTabs": null
            },
            "signInEachLocation": null,
            "offlineAttributes": null,
            "requireSignerCertificate": null,
            "requireSignOnPaper": null,
            "canSignOffline": null,
            "isBulkRecipient": null,
            "bulkRecipientsUri": null,
            "recipientSuppliesTabs": null,
            "excludedDocuments": null,
            "name": "name",
            "email": "emailid",
            "emailRecipientPostSigningURL": null,
            "signingGroupId": null,
            "signingGroupName": null,
            "signingGroupUsers": null,
            "recipientId": "2044556663",
            "recipientIdGuid": null,
            "accessCode": null,
            "addAccessCodeToEmail": null,
            "requireIdLookup": null,
            "idCheckConfigurationName": null,
            "socialAuthentications": null,
            "phoneAuthentication": null,
            "samlAuthentication": null,
            "smsAuthentication": null,
            "userId": null,
            "clientUserId": null,
            "embeddedRecipientStartURL": null,
            "customFields": null,
            "routingOrder": "1",
            "idCheckInformationInput": null,
            "recipientAttachments": null,
            "note": null,
            "roleName": null,
            "status": null,
            "signedDateTime": null,
            "deliveredDateTime": null,
            "declinedDateTime": null,
            "sentDateTime": null,
            "declinedReason": null,
            "deliveryMethod": null,
            "faxNumber": null,
            "templateLocked": null,
            "templateRequired": null,
            "emailNotification": null,
            "inheritEmailNotificationConfiguration": null,
            "errorDetails": null,
            "recipientAuthenticationStatus": null,
            "totalTabCount": null
        }
    ],
    "agents": null,
    "editors": null,
    "intermediaries": null,
    "carbonCopies": null,
    "certifiedDeliveries": null,
    "inPersonSigners": null,
    "recipientCount": null,
    "currentRoutingOrder": null,
    "errorDetails": null
},
"customFields": {
    "textCustomFields": [{
            "fieldId": "788788",
            "name": "AppNumber",
            "show": "false",
            "required": "false",
            "value": "788788",
            "configurationType": null,
            "errorDetails": null
        }
    ],
    "listCustomFields": null
},
"eventNotification": null,
"brandId": "BrandId",
"allowRecipientRecursion": null,
"templateId": null,
"templateRoles": null,
"compositeTemplates": null,
"accessibility": null,
"transactionId": null,
"status": "sent",
"documentsUri": null,
"recipientsUri": null,
"asynchronous": null,
"envelopeUri": null,
"emailSubject": "ABC Agreement",
"emailBlurb": "Please Sign",
"envelopeId": null,
"signingLocation": null,
"customFieldsUri": null,
"envelopeIdStamping": null,
"authoritativeCopy": null,
"notification": {
    "useAccountDefaults": null,
    "reminders": {
        "reminderEnabled": "true",
        "reminderDelay": "1",
        "reminderFrequency": "2"
    },
    "expirations": {
        "expireEnabled": "true",
        "expireAfter": "2",
        "expireWarn": "1"
    }
},
"notificationUri": null,
"enforceSignerVisibility": null,
"enableWetSign": null,
"allowMarkup": null,
"allowReassign": null,
"createdDateTime": null,
"lastModifiedDateTime": null,
"deliveredDateTime": null,
"sentDateTime": null,
"completedDateTime": null,
"voidedDateTime": null,
"voidedReason": null,
"deletedDateTime": null,
"declinedDateTime": null,
"statusChangedDateTime": null,
"documentsCombinedUri": null,
"certificateUri": null,
"templatesUri": null,
"messageLock": null,
"recipientsLock": null,
"useDisclosure": null,
"emailSettings": null,
"purgeState": null,
"lockInformation": null,
"is21CFRPart11": null
}

2)如果在任何情况下,如果您发现.off()。unbind()或.stopPropagation()无法解决您的问题,请使用.stopImmediatePropagation()。它通常在这种情况下非常有用,因为您只希望在没有任何冒泡的情况下处理事件并且不影响已经处理的任何其他事件。类似的东西:

$('table').unbind("click").click('.up,.down,.top,.bottom') {
     //Do Stuff
});

$('table').off("click").on('click', ".up,.down,.top,.bottom", function() {
     //Do Stuff
});

总能做到这一点!