【发布时间】:2015-05-02 19:46:19
【问题描述】:
我写了一个函数 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' );
}
} );
当用户更改选择的值时,我的条件完美运行,它显示了它应该做什么。但是用户可以点击一个链接,该链接再次触发 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 标签,您只需要添加“onchange”事件侦听器,但我不知道如何在用户单击链接时检查此条件,页面不会重新加载 - 它只显示或隐藏一些类。 我无法检查“onclick”函数中选择字段的值,因为我自动为所有链接创建了所有“onclick”函数。
所以实现我的目标的唯一方法是为函数添加某种事件侦听器,每次调用函数时都会检查条件并执行某些操作。
【问题讨论】:
标签: javascript function conditional-statements