每次调用函数后都要检查条件

Check the conditions every time after function has been called

本文关键字:检查 条件 调用 函数      更新时间:2023-09-26

我写了一个函数show(),它揭示了隐藏的id类(我知道有jquery和其他方法可以做到这一点,但我希望这样做)。

//-------------------------
// Function show()
//-------------------------
/**
 * Changes element class name from hide to show in parent element [ default: content ] and hides every other shown classes in that parent element.
 * @param { string } id || none to show  
 * @param { string } parent element id, if provided changes default [ optional ]
 * @params { string } more elements id's to be shown [ optional ]
 * @return { void } changed classes names
**/

我有html选择:

<select name="productName" id="productName">
    <option value="none" selected>Choose product</option>
    <option value="product01">product01</option>
    <option value="product02">product02</option>
    <option value="product03">product03</option>
</select>

在上面我有一个事件监听器,它显示了一组通常隐藏的div:

document.getElementById( 'productName' ).addEventListener( 'change', function() {
    if( document.getElementById( 'productName' ).value != 'none' ) {
        if( document.getElementById( 'productName' ).value != 'none' && document.querySelectorAll( '.show' )[ 1 ].id ) show( document.querySelectorAll( '.show' )[ 1 ].id, 'content', 'showProductData' );
    }
} );

当用户更改select的值时,我的条件非常有效,并且它显示了它应该做什么。但是,用户可以点击一个链接,再次触发show()函数并更改他的视图,然后我的问题就出现了。

select标记的onchange事件是显而易见的,当用户点击锚点并更改页面内容时,它不会触发。

因此,我需要检查是否调用了show()函数,如果调用了,则再次检查以下条件:

    if( document.getElementById( 'productName' ).value != 'none' && document.querySelectorAll( '.show' )[ 1 ].id ) {
        show( document.querySelectorAll( '.show' )[ 1 ].id, 'content', 'showProductData' );
    }

是否可以在不干扰show()函数的情况下执行此操作?

当然,setInterval可以检查这个条件,但它会改变每个间隔时间显示的内容。

每次调用show()函数后,我只需要检查一次这个条件。也许有什么棘手的方法可以让事件监听器进入函数?类似于:

show().addEventListener( 'called', function () { above condition } );

或者任何其他方法在每次调用函数show()后检查select标记的值?

编辑。我不会删除所有的帖子,但可能我应该删除。我会尽力澄清我的问题。

从清晰和直接的角度来看,我的例子可能与我的问题无关。

每次调用该函数,以及每次用户单击链接或从select标记中选择内容时调用该函数时,我都需要检查条件。虽然使用select标记,您只需要添加"onchange"事件侦听器,但我不知道如何在用户单击链接时检查此条件,页面不会重新加载-它只显示或隐藏一些类。我无法检查"onclick"函数中select字段的值,因为我会自动为所有链接创建所有"onclick'"函数。

因此,实现我的目标的唯一方法是为函数添加某种事件侦听器,每次调用函数时都会检查条件并执行某些操作。

如果我理解正确,您想在动态更改值时触发更改事件吗?容易的

var elem = document.getElementById('productName');
//Do what you need to do to change value.
var event = new Event('change');  // Create a new event
elem.dispatchEvent(event); // Fire the event on the element.