必须单击动态添加的按钮(使用jQuery)两次才能触发已绑定到按钮的click事件

时间:2011-06-21 16:13:37

标签: jquery button click

我动态添加一个可以单击的选择按钮,从附加到表格的列表中选择一个给定的联系人。

在点击动态添加的按钮之前,我必须单击文档中的任意位置。显然,动态按钮的绑定事件直到第一次单击后才会绑定。

BTW,在当前版本的函数中,我将click事件绑定到每个动态按钮的文档正文,然后查看事件目标是否是相关的动态按钮,此时我触发所需的函数传回选定的联系人。我转而采用这种方法,给予其他人体验我在这里描述的同样的建议。在此实现之前,我有一个非常传统的$ J(“#btnId”)。bind('click',{....},function(event){...});绑定click事件的方法,这导致在点击事件触发动态按钮之前必须单击两次的相同体验。我也是从其他角度来看这个,使用jQuery的.bind,.live,.delegate方法,并且在所有情况下,我必须在按钮的click事件实际触发之前单击两次。

function PickContacts() {
    if ($J("#tblCp").length > 0) {
        var broad = $J("#chkCpBroad").prop("checked");
        var contactType = GetCheckBoxListValues("divCpContactType");
        var contactId = "";
        if ($J("#txtCpContactId").length > 0) {
            contactId = $J("#txtCpContactId").val();
        }
        var contactName = $J("#txtCpContactName").val();
        var firstName = $J("#txtCpFirstName").val();
        var lastName = $J("#txtCpLastName").val();
        var email = $J("#txtCpEmail").val();
        var allMatches = $J("#chkCpAllMatches").prop("checked");
        var rows = ParseInts($J("#txtCpRowsReturned").val(), 10);
        if (rows === 0) {
            rows = 15;
        }
        var crmSeatsOnly = false;
        if (cpCrmSeatsOnly !== null && cpCrmSeatsOnly === "Y") {
            crmSeatsOnly = true;
        }
        var tbl = $J("#tblCpResults");
        tbl.empty();
        if (contactId !== "" || contactName !== "" || firstName !== "" || lastName !== "" || email !== "") {
            $J.ajax({
                type: "POST",
                url: "/ClientBin/Contact.asmx/ContactPicker",
                data: "{'broad':" + broad + ",'contactType':'" + contactType + "','contactId':'" + contactId + "','contactName':'" + contactName + "','firstName':'" + firstName + "','lastName':'" + lastName + "','email':'" + email + "','allMatches':" + allMatches + ",'crmSeatsOnly':" + crmSeatsOnly + ",'rows':" + rows + "}",
                contentType: "application/json; charset=utf-8",
                context: tbl,
                success: function (result) {
                    if (result.d !== "TIME OUT") {
                        var JObject = ParseJson(result.d);
                        if (JObject !== null) {
                            if (JObject.RESULT[0].SUCCESS) {
                                var alternatingRow = false;
                                var c = JObject.CONTACT;
                                for (i = 0; i < c.length; i++) {
                                    var trStyle = "rowstyleNoBorder";
                                    if (alternatingRow) {
                                        trStyle = "alternatingrowstyleNoBorder";
                                        alternatingRow = false;
                                    }
                                    else {
                                        alternatingRow = true;
                                    }

                                    this.append('<tr class="' + trStyle + '"><td><span id="lblCpContactId' + i + '">' + c[i].CONTACT_ID + '</span></td><td><span id="lblCpContactName' + i + '">' + c[i].CONTACT_NAME + '</span></td><td><span id="lblCpFirstName' + i + '">' + c[i].FIRST_NAME + '</span></td><td><span id="lblCpLastName' + i + '">' + c[i].LAST_NAME + '</span></td><td valign="top"><input type="submit" id="btnCpSelect' + i + '" value="' + $J("#hdnCpTransSelect").val() + '" title="' + $J("#hdnCpTransSelectContact").val() + '" /></td></tr>');

                                    $J("body").bind('click', { index: i, contactId: c[i].CONTACT_ID, contactName: c[i].CONTACT_NAME, firstName: c[i].FIRST_NAME, lastName: c[i].LAST_NAME }, function (event) {
                                        if ($J(event.target).is("#btnCpSelect" + event.data.index)) {
                                            SelectContact(event.data.contactId, event.data.contactName, event.data.firstName, event.data.lastName);
                                            return false;
                                        }
                                    });
                                    // Copy button css styling from an existing on page button by passing the IDs for both buttons to the CopyBtnStyle fn.
                                    CopyBtnStyle("btnCpSelect" + i, "btnCpClose");
                                }
                            }
                            else {
                                this.append('<tr><td><span id="lblCpNoRows">' + JObject.RESULT[0].FEEDBACK + '</span></td></tr>');
                            }
                        }
                    }
                    else {
                        TimeOut();
                    }
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    WsFail(XMLHttpRequest, textStatus, errorThrown);
                }
            });
        }
    }
}

2 个答案:

答案 0 :(得分:2)

好吧......我在这里找到了最重要的事情。我不确定技术上为什么这是一个问题,也许这里有一个知识渊博的贡献者可以为我解释,但我必须点击这两个动态按钮来触发点击事件的问题是由于我已经连接了我的“PickContacts”JS函数来调用keyup并模糊表单中文本输入字段的事件。

虽然显然有点多余,但我不确定为什么这会出现问题,因为在我调用WS方法检索联系人列表之前,我会清空表格,其中显示由WS方法发回的结果。所以,我会假设随着表行和它们的元素从DOM中删除,在键盘上或模糊时绑定到动态按钮的click事件也是如此(以先到者为准)。

我可以肯定地说,我可以观察到的是,在我从文本输入字段中删除其中一个事件后,将其他任何一个留在原地,我的问题是必须在获取之前点击两次解决按钮的点击事件。

如果有人在技术上知道为什么通过绑定这两个事件来调用这个构建列表的函数会产生问题,我希望在基础层面上更好地理解它。

无论如何,我再次感谢PetersonDidIt和DarthJDG给予的关注。

答案 1 :(得分:1)

你可以做很多事情来使这项工作更好。我重新编写了一些代码并添加了很多注释来试图解释我为什么要进行更改:http://jsbin.com/ipuki5/2/edit

或群发代码块:

// Create an easy to edit template for our row
var contactsRowtmpl = '<tr class="%trStyle%"><td><span id="lblCpContactId%index%">%CONTACT_ID%</span></td>'+
    '<td><span id="lblCpContactName%index%">%CONTACT_NAME%</span></td>'+
    '<td><span id="lblCpFirstName%index%">%FIRST_NAME%</span></td>'+
    '<td><span id="lblCpLastName%index%">%LAST_NAME%</span></td>'+
    '<td valign="top"><input type="submit" id="btnCpSelect%index%" class="CpSelect" value="%value%" title="%title%" /></td></tr>';

// Very simple templating function
function template( tmpl, data ) {
  return tmpl.replace(/%(\w*)%/g,function(){ return data[ arguments[1] ] || "";});
}

// Cache the table selector 
var tblCpResults = $J("#tblCpResults");
// Use delegate to bind the click event to for all input.CpSelet  
tblCpResults.delegate("click", ".CpSelect", function (event) {
  // prevent the default action of the click event
  event.preventDefault();
  // retrive the data from the row
  var data = $( this ).closest("tr").data("contact");
  // Select the contact
  SelectContact(data.contactId, data.contactName, data.firstName, data.lastName);
});

function PickContacts() {
    if ($J("#tblCp").length > 0) {
        var broad = $J("#chkCpBroad").prop("checked");
        var contactType = GetCheckBoxListValues("divCpContactType");
        var contactId = "";
        if ($J("#txtCpContactId").length > 0) {
            contactId = $J("#txtCpContactId").val();
        }
        var contactName = $J("#txtCpContactName").val();
        var firstName = $J("#txtCpFirstName").val();
        var lastName = $J("#txtCpLastName").val();
        var email = $J("#txtCpEmail").val();
        var allMatches = $J("#chkCpAllMatches").prop("checked");
        var rows = ParseInts($J("#txtCpRowsReturned").val(), 10);
        if (rows === 0) {
            rows = 15;
        }
        var crmSeatsOnly = false;
        if (cpCrmSeatsOnly !== null && cpCrmSeatsOnly === "Y") {
            crmSeatsOnly = true;
        }

        tblCpResults.empty();
        if (contactId !== "" || contactName !== "" || firstName !== "" || lastName !== "" || email !== "") {
            $J.ajax({
                type: "POST",
                url: "/ClientBin/Contact.asmx/ContactPicker",
                // Use a normal object here much easier to maintain
                data: {
                  'broad': broad,
                  'contactType': contactType,
                  'contactId': contactId,
                  'contactName': contactName,
                  'firstName': firstName,
                  'lastName': lastName,
                  'email': email,
                  'allMatches': allMatches,
                  'crmSeatsOnly': crmSeatsOnly,
                  'rows': rows
                },
                contentType: "application/json; charset=utf-8",
                success: function (result) {
                    if (result.d === "TIME OUT") {
                      TimeOut();
                      return;
                    }
                    var JObject = ParseJson(result.d),
                        // Cache these selectors so we don't have to reselect them in the for loop
                        hdnCpTransSelect = $J("#hdnCpTransSelect"),
                        hdnCpTransSelectContact = $J("#hdnCpTransSelectContact");
                    if (JObject !== null) {
                        if (!JObject.RESULT[0].SUCCESS) {
                          tblCpResults.append('<tr><td><span id="lblCpNoRows">' + JObject.RESULT[0].FEEDBACK + '</span></td></tr>');
                          return;
                        }
                        var c = JObject.CONTACT;
                        // Create an empty jQuery object to stuff all of the rows in
                        var rows = $();
                        for (i = 0; i < c.length; i++) {
                          c[ i ].trStyle = ( i % 2 ) ? "alternatingrowstyleNoBorder" : "rowstyleNoBorder";
                          c[ i ].index = i;
                          c[ i ].value = hdnCpTransSelect.val();
                          c[ i ].title = hdnCpTransSelectContact.val();

                          // Use the template function to handle creating our row
                          var row = template( contactsRowtmpl, c[ i ] );
                          // Add the contacts data to the row so we can retrive it later
                          $.data( row, "contact", c[ i ] );
                          // add the row to the rows jQuery object
                          rows = rows.add( row );
                          // Why do you need to copy the btn style? seems like this could be improved on.
                          CopyBtnStyle("btnCpSelect" + i, "btnCpClose");
                        }
                        // Now that we are done looping add all the rows to the dom.
                        tblCpResults.append( rows );
                    }
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    WsFail(XMLHttpRequest, textStatus, errorThrown);
                }
            });
        }
    }
}