首页 > 解决方案 > Ionic 为动态创建的 div 添加点击功能

问题描述

从我的代码中,我有一个可以多次创建 div 元素的函数(使用surroundContents()),我怎样才能使这些创建的 div 元素在同一页面的类中触发一个函数?

更准确地说,我需要这些 div 元素中的任何一个(使用 function 创建createDiv())能够通过单击调用的函数来触发,clickCreatedDiv(arg)并将MyPage class任何字符串作为参数传递。我已经尝试过了,element.setAttribute('(click)', 'clickCreatedDiv()');但没有成功。我怎样才能实现这种行为?

export class MyProvider {
  wrapSelection(comment) {
    let element = document.createElement("div")
    element.setAttribute('(click)', 'clickCreatedDiv()');
    element.surroundContents(element);
  }
}

import { MyProvider } from '../../providers/my-provider';
@Component({
    selector: 'page-mypage',
    templateUrl: 'mypage.html',
}) 
export class MyPage {
  constructor(public myprovider: MyProvider) {}
  createDiv() {
    this.myprovider.wrapSelection();
  }

  clickCreatedDiv(arg) { // This is what I want to trigger with click
    alert('click ' + arg);
  }
}

标签: javascriptangulartypescriptionic-framework

解决方案


我会将 click 函数作为回调传递给 wrapSelection。例如:

export class MyProvider {
  wrapSelection(comment, onClick) {
    let element = document.createElement("div")
    element.setAttribute('(click)', onClick);
    element.surroundContents(element);
  }
}

export class MyPage {
  constructor(public myprovider: MyProvider) {}
  createDiv() {
    this.myprovider.wrapSelection('Some comment', this.clickCreatedDiv);
  }

  clickCreatedDiv(arg) { // This is what I want to trigger with click
    alert('click ' + arg);
  }
}

推荐阅读