如何将点击事件添加到打字稿中动态添加的html元素
Posted
技术标签:
【中文标题】如何将点击事件添加到打字稿中动态添加的html元素【英文标题】:How to add click event to dynamically added html element in typescript 【发布时间】:2017-07-30 06:53:06 【问题描述】:我正在用 Angular 2 构建一个应用程序。我想将点击事件添加到动态添加的 html 元素中。 我定义了一个字符串(contentString),在这个字符串中我定义了html元素。
var contentString = '<b>' + this.mName + '</b><br/> ' + this.mObject.category + '<br/> Click here for more information <button (click)="navigate()">Navigate here</button>';
这个字符串被放在一个像这样的html元素中:
var boxText = document.createElement("div");
boxText.innerHTML = contentString;
虽然当我检查元素时,它定义了点击事件,但它没有触发。
点击它应该控制台日志
navigate()
console.log("eeeehnnananaa");
但这不起作用。 有人解决吗?
【问题讨论】:
为什么不用angular来添加html? @MujtabaKably 你会怎么做?我不知道怎么写那个代码 ***.com/questions/36116770/… 我想这会解决你的问题。 【参考方案1】:Angular 在组件编译时处理模板。以后添加的 HTML 不再编译,绑定被忽略。
你可以使用
constructor(private elRef:ElementRef)
ngAfterViewInit()
// assume dynamic HTML was added before
this.elRef.nativeElement.querySelector('button').addEventListener('click', this.onClick.bind(this));
【讨论】:
仅供参考 - 不知道为什么,但 addEventHandler 返回“不是函数”错误。使用 addEventListener 并且效果很好! @firas489 非常感谢您的提示。那是个错误。我修好了。 TypeScript != Angular. @AntonyBooth 这个问题有 Angular 标签,即使标题只提到 Typescript ;-)【参考方案2】:就我而言,我做这些--
var boxText = document.createElement("div");
const contentString = '<b>' + this.mName + '</b><br/> ' + this.mObject.category +
'<br/> Click here for more information ';//as per your code
boxText.innerHTML = contentString;
const button = document.createElement('button');
button.addEventListener('click', (e) =>
this.navigate();//your typescript function
);
button.innerText = 'Navigate here';
boxText.appendChild(button);
【讨论】:
【参考方案3】:Call click event dynamically
ConfirmThisOrder(obj)
var orderItemID = obj.target.dataset.oid;
ItemDetails(orderId, itemIndex)
if ($("#accordionNew" + itemIndex).closest("div").html().indexOf("div_" + orderId) == -1)
this.oRequest = new ORequestParameter();
var retrievedObject = localStorage.getItem('userObject');
let userObject = JSON.parse(retrievedObject) as AdminDashboardModel;
this.oRequest.SellerId = userObject.sellerId;
this.oRequest.OrderStatus = $("#hdnOrderStatus").val().toString();
this.oRequest.OrderId = orderId;
this.oRequest.OrderConfirmationFlag = '0,1,2';
let sProviderId = "0";
if (this.MultiSelectObjTypeSelected != undefined)
let result2 = this.MultiSelectObjTypeSelected.map(a => a.id);
if (result2.join().length > 0)
sProviderId = result2.join();
this.oRequest.ProviderID = sProviderId;
this.orderService.GetItemDetails(this.oRequest).subscribe(
lstOrderItem =>
this.lstOrderItem = lstOrderItem;
var sData = "";
if (this.lstOrderItem.length > 0)
sData += "<div class='col-4 col-lg-4 col-md-4 col-xs-4 text-left' style='font-weight: bold;' id='div_" + orderId + "'>Product Name</div>";
sData += "<div class='col-4 col-lg-4 col-md-4 col-xs-4 text-center' style='font-weight: bold;'>Price</div>";
sData += "<div class='col-4 col-lg-4 col-md-4 col-xs-4 text-center' style='font-weight: bold;'></div>";
sData += "<div class='clearfix'></div>";
var aTag = document.createElement('a');
for (var i = 0; i < this.lstOrderItem.length; i++)
sData += "<div style='background-color:#fff;padding:10px 0;'>";
sData += "<div class='col-4 col-sm-4 col-lg-4 col-xs-4 col-md-4'>";
sData += "<span style='text-align: justify;'>" + this.lstOrderItem[i].productName + "</span>"; /*<b style='color:red;' > (" + this.lstOrderItem[i].productType + ") < /b>*/
sData += "</div>";
sData += "<div class='col-4 col-sm-4 col-lg-4 col-xs-4 col-md-4 text-center'>";
sData += "<span><i class='fa fa-inr'></i> " + this.lstOrderItem[i].providerSellingPrice + "</span>";
sData += "</div>";
sData += "<div class='col-4 col-lg-4 col-md-4 col-xs-2 text-center' style='font-weight: bold;'>";
sData += '<a id="btn_' + this.lstOrderItem[i].orderItemID + '" data-oid=' + this.lstOrderItem[i].orderItemID + ' class="mylink btn btn-success" style="width:70px;">Pending</a>';
sData += "</div>";
sData += "</div>";
sData += "<div class='clearfix'></div>";
sData += "<div style='background-color:#BFE7FF;padding:15px 0;'>";
sData += "<div class='col-6 col-sm-6 col-lg-6 col-xs-6 col-md-6' style='font-weight: bold'>Total Billed Amount</div>";
sData += "<div class='col-2 col-sm-2 col-lg-2 col-xs-2 col-md-2 pull-right text-right'>";
sData += "<span><b>Price:</b> <i class='fa fa-inr'></i> " + totalAmount + "</span></div>";
sData += "<div class='clearfix'></div>";
sData += "</div>";
else
$("#errorMsg").removeClass("hidden");
$("#errorMsg").addClass("alert-danger");
$("#errorMsg").html("There was no record found");
$("#accordionNew" + itemIndex).closest("div").html(sData);
let children = document.getElementsByClassName("mylink");
for (let i = 0; i < children.length; i++)
children[i].addEventListener("click", (event: Event) =>
this.ConfirmThisOrder(event);
);
,
error => this.errorMessage = <any>error
);
return false;
【讨论】:
以上是关于如何将点击事件添加到打字稿中动态添加的html元素的主要内容,如果未能解决你的问题,请参考以下文章