javascript - 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);
}
}
解决方案
我会将 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);
}
}
推荐阅读
- java - Kibana 启用了您当前浏览器不符合的严格安全要求
- python - Python - 在 Windows 上获取实际文件名(使用正确的大小写)?
- elasticsearch - Jmeter对ElasticSearch的http请求中的三引号
- python - 进行价值选择的最快方法?
- python-3.x - python中sorted()函数背后的逻辑
- flutter - 在 Flutter 中使用 Dio 包下载多个文件
- flutter - 如何将 Flutter 应用设置为默认短信应用?
- javascript - 如何不对所有选择激活选择功能
- swift - 按钮stackView间距不起作用-Swift-以编程方式
- c# - 通过 lambdada 表达式在组中选择当前记录