将click事件附加到动态元素也会为所有父元素触发

时间:2015-02-26 16:31:20

标签: javascript jquery asp.net-mvc

我从服务器获取数据后创建了一个动态表。

表格的每一行都有a标记,我试图附加点击事件。

代码块下面的

显示了动态表的创建。

function ProcessResponseData(Row) {
    var wrptr = CreateDynamicElement('tr', '', '');
    wrptr.append(CreateDynamicElement('td', Row.HeaderID, '')); // Row. Same property name mentioned in response class
    wrptr.append(CreateDynamicElement('td', Row.DealID, ''));
    wrptr.append(CreateDynamicElement('td', Row.CustomerName, ''));
    wrptr.append(CreateDynamicElement('td', Row.InvoiceNo, ''));
    wrptr.append(CreateDynamicElement('td', Row.ManufacturerID, ''));
    wrptr.append(CreateDynamicElement('td', Row.Make, ''));
    wrptr.append(CreateDynamicElement('td', Row.AssetModel, ''));
    var ancTd = CreateDynamicElement('td', '', '');
    ancTd.append(CreateDynamicElement('a', 'Validate', Row.HeaderID))
    wrptr.append(ancTd);

    wrptr.attr('WebserviceID', Row.WebServiceID);
    wrptr.attr('DealID', Row.DealID);
    wrptr.attr('MultipleProdID', Row.MultipleProdID);
    $('#tblSerialData').append(wrptr);
}

下面的函数创建元素。

function CreateDynamicElement(tagName, tagData, ActionAppendData) {

    var element = $(document.createElement(tagName));

    if (tagName == 'td') {
        tagData = (tagData != null ? tagData : '');
        element.text(tagData);
    }

    if (ActionAppendData != null || ActionAppendData != '') {
        element.text(tagData);
         //attaching the click event here to a tag    
        element.live('click', function (e) {
            ShowPopUp(ActionAppendData, this);
               e.stopPropagation(); // this has stopped the bubble but still it is getting attached to the tr rather than the a tag??
        });



    }
    return element;
}

我面临的问题是整个行被触发了。该事件已附加到tr> td> a

任何解决此问题的建议。

1 个答案:

答案 0 :(得分:0)

使用event.stopPropagation()。请参阅event.stopPropagation()

相关问题