[英]Knockout click binding fires after second click
I have a knockout binding that scrolls to a part if the page on click with this function 如果单击带有此功能的页面,则我具有一个可剔除到页面上的部分的剔除绑定
scrollTo() {
$("a.scroll").click(function(event) {
event.preventDefault();
$('body').animate({
scrollTop: $(this.hash).offset().top
}, 500);
});
}
The html where i call the function 我在其中调用函数的html
<a class="scroll icon-arrow-down" href="#part" data-bind="localizedText: { id: '4-anchor-1', html: true }, tap: controller.scrollTo.bind(controller)"></a>
The problem is that it fires after the second click and not the first. 问题是它在第二次单击而不是第一次单击后触发。 Also this happen when coming on the page when you click a button it does not fire click it again it fires and then it function normally on other button to.
当您单击页面上的某个按钮时,它也不会触发,再次单击它会触发,然后在其他按钮上正常运行时,也会发生这种情况。
The issue is because on the first click you call scrollTo()
which binds the event. 问题是因为在第一次单击时,您调用
scrollTo()
绑定了事件。 Then on the next and each successive click you add another click()
handler as well as execute all previous click
event handlers. 然后在下一次和每次连续单击时,添加另一个
click()
处理程序并执行所有先前的click
事件处理程序。 You just need to remove the scrollTo()
function and add the event on load: 您只需要删除
scrollTo()
函数并在加载时添加事件:
<a class="scroll icon-arrow-down" href="#part" data-bind="localizedText: { id: '4-anchor-1', html: true }"></a>
$("a.scroll").click(function(event) {
event.preventDefault();
$('body').animate({
scrollTop: $(this.hash).offset().top
}, 500);
});
Alternatively, if the a
element is appended to the DOM dynamically you would need to use a delegated event handler: 或者,如果将
a
元素动态附加到DOM,则需要使用委托的事件处理程序:
$(document).on('click', "a.scroll", function(event) {
event.preventDefault();
$('body').animate({
scrollTop: $(this.hash).offset().top
}, 500);
});
Since you're using Knockout, don't use the jQuery event bindings. 由于您使用的是淘汰赛,因此请勿使用jQuery事件绑定。 Assuming you have defined a
tap
binding handler (which is to say, to call an event handler like click
does), your HTML markup is fine. 假设您已经定义了
tap
绑定处理程序(也就是说,像click
一样调用事件处理程序),那么您的HTML标记就可以了。 Just turn your scrollTo
method into an event handler. 只需将您的
scrollTo
方法变成事件处理程序即可。
scrollTo(event) {
event.preventDefault();
$('body').animate({
scrollTop: $(this.hash).offset().top
}, 500);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.