【问题标题】:Is there any equivalent for $(".class").click(); in Typescript?$(".class").click(); 是否有任何等价物?在打字稿中?
【发布时间】:2019-03-25 14:28:09
【问题描述】:

我在角度使用日期范围选择器。

<button type="button" class="btn btn-danger daterange-ranges">
<i class="icon-calendar22 position-left"></i> <span></span> 
<b class="caret"></b>
</button>

当我点击它时,我会在下拉菜单中选择日期范围,其中包含一个“applyBtn”类的应用按钮。

在 JQuery 中有一个选项 $(".class").click(); 来获取 onclick 函数。 我不能写(click)="getdateRange()"。打字稿中$(".class").click(); 是否有任何等价物?

我想要类似的东西,

$(".applyBtn").click(function(){ alert("The button was clicked."); });

【问题讨论】:

标签: jquery angular typescript


【解决方案1】:

你可以使用纯 javascript 来做到这一点

    document.querySelector('.applyBtn').addEventListener('click', () => {
       alert("The button was clicked.");
    });

它将与 JQuery 中的 $(".applyBtn").click(); 做同样的事情

【讨论】:

  • 但是你写的不是函数。我想要类似$(".applyBtn").click(function(){ alert("The button was clicked."); });
  • 这里有什么问题为什么你不能这样做document.querySelector('.applyBtn').addEventListener('click', (event) =&gt; { alert("The button was clicked."); });
  • 你可以在你的 ngOnInit 或另一个生命周期钩子中添加它
【解决方案2】:

正如我在标签中看到的,您使用的是 Angular。在 Angular 中使用 jQuery 并不是一个好主意,因为它有自己很棒的工具。

要制作点击处理程序,您需要执行以下操作

<anyTag (click)="clickHandler($event)"></anyTag>

然后在你的组件中粘贴下一个:

public clickHandler(event) {
  //do whatever you want
}

如果你想知道$event 传递了什么,欢迎使用 angular.io API

附:如果你想重复使用它,你需要把它变成一个额外的组件,比如date-picker.component.ts,然后粘贴到那里。然后您可以通过[date]="date" 将表单的值传递给创建的组件并在组件@Input() date; 中检索它。

您还可以通过

向父级发送值
@Output() emitter = new EventEmitter();

public emitValue(): void {
  this.emitter.emit(value);
}

并在父组件中获取发射值 &lt;app-picker (emitter)="handleEmit($event)&gt;&lt;/app-picker&gt;

父组件.ts

public handleEmit(event) {
  //do something
}

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2015-05-19
  • 1970-01-01
  • 2018-07-06
  • 2020-10-29
  • 2011-07-14
  • 2014-02-26
  • 1970-01-01
  • 2016-04-06
相关资源
最近更新 更多