嵌套按钮:如何实现单独的功能

时间:2017-11-06 01:55:31

标签: javascript button onclick nested

我在父按钮后附加了一个按钮:

// Add Payment method to Customer.
                        customerPaymentProfileType opaquePaymentProfile = new customerPaymentProfileType();
                        opaquePaymentProfile.payment = paymentType;
                        opaquePaymentProfile.customerType = customerTypeEnum.individual;
                        var request2 = new createCustomerPaymentProfileRequest
                        {
                            paymentProfile = opaquePaymentProfile,
                            validationMode = validationModeEnum.none,
                            customerProfileId = userID.ToString()
                        };
                        var controller2 = new createCustomerPaymentProfileController(request2);
                        controller2.Execute();

                        //Send Request to EndPoint
                        createCustomerPaymentProfileResponse response2 = controller2.GetApiResponse();
                        if (response2 != null && response2.messages.resultCode == messageTypeEnum.Ok)
                        {
                            if (response2 != null && response2.messages.message != null)
                            {
                                //Console.WriteLine("Success, createCustomerPaymentProfileID : " + response.customerPaymentProfileId);
                            }
                        }
                        else
                        {
                            Utility.AppendTextToFile("Error: " + response.messages.message[0].code + "  " + response.messages.message[0].text, Server.MapPath("/pub/auth.txt"));

                        }

我想为child_button创建独立于parent_button的功能:

var parent_button = document.createElement("button");
var child_button = document.createElement("button");
parent_button.appendChild(child_button);

但是考虑到这段代码,每当我点击child_button时,我都必须触发parent_button.onclick()。我如何将两者分开?

重叠按钮如下所示:

enter image description here

1 个答案:

答案 0 :(得分:2)

在子按钮的事件对象上使用stopPropagation()。它将阻止事件从子级传播到父级。

你可以在这里看到一个例子:



var pb = document.getElementById("pb");
var cb = document.getElementById("cb");
pb.addEventListener("click", function(e) {
  console.log("Parent");
});
cb.addEventListener("click", function(e) {
  console.log("Child");
  e.stopPropagation();
})

<button id="pb">Parent Button <button id="cb">Child Button</button></button>
&#13;
&#13;
&#13;

注意:我认为默认行为是当您单击子元素时,应触发子元素和父元素的事件,但在此示例中,这不会发生;也许它是按钮作为父母特有的东西。