如何使用OR操作符构建事件侦听器和if语句

How to build an event listener and an if statements with an OR operator?

本文关键字:侦听器 if 语句 事件 构建 何使用 OR 操作符      更新时间:2023-09-26

因为我不想写我的函数两次,如果单击.customer或字符串'customer'是url的一部分,我想执行一些代码。

像这样:

$('.customer').click(function() {

if ( document.location.href.indexOf('#customer') > -1 ) {

有什么好的方法可以做到这一点?

一种方法是将将要执行的逻辑抽象到一个新函数中,然后在任何一种情况下都只调用该函数。这样做的好处是可读性和便于将来扩展(如果您想添加另一种情况,某些代码应该被执行)。

代码应该是这样的:

$(document).ready(function()
{
    function logicToBeExecuted()
    {
        // Logic goes in here
    }
    if (document.location.href.indexOf('#customer') > -1 ) {
        logicToBeExecuted();
    }
    $('.customer').click(function()
    {
        logicToBeExecuted();
    }
});

你可以将所有将要执行的代码包装成一个函数并为每个侦听器调用该函数

$('.customer').click(function() { 
     myFunction(); 
});
if ( document.location.href.indexOf('#customer') > -1 ) {
     myFunction(); 
});