简体   繁体   English

如果函数不返回false?

[英]If function doesn't return false?

I have the following click event: 我有以下click事件:

$('#planung').click(function(){
    if($current != $('#planungtext')){
        console.log($current);
        console.log($('#planungtext'));
        $($current).removeClass('active');
        setTimeout(function(){$('#planungtext').addClass('active')}, 1000);
        $current = $('#planungtext');
    }
});

I used the log to see the contents of my variable and the '#planungtext' element. 我使用日志来查看变量和'#planungtext'元素的内容。 They are exactly the same, but the if function doesn't work as desired, as it is still going into it. 它们是完全相同的,但是if函数不能按预期运行,因为它仍在运行。

$current is not set before the first time the element is clicked. 第一次单击该元素之前未设置$ current。

Am I doing something wrong here? 我在这里做错什么了吗?

The two jQuery objects point at the same DOM elements, but are different arrays (jQuery objects are essentially just arrays behind the scenes with extra stuff ). 两个jQuery对象指向相同的DOM元素,但是它们是不同的数组(jQuery对象本质上只是幕后的数组, 带有多余的东西 )。

Use jQuery is http://api.jquery.com/is/ to test if the same selector would match them: 使用jQuery is http://api.jquery.com/is/来测试相同的选择器是否可以匹配它们:

if(!$current.is('#planungtext')){

The fastest way to do that check "manually" is: “手动”进行检查的最快方法是:

if ($current[0].id !== '#planungtext'){

It is mentioned in comment that $current is a jQuery variable (good naming standard) but initially undefined in which case almost every solution posted will crash. 在评论中提到$ current是一个jQuery变量(良好的命名标准),但最初undefined在这种情况下,几乎所有发布的解决方案都将崩溃。 You need to initialise $current to an empty jQuery object to give the most consistent behavior (jQuery objects should never be undefined to be used like that, else you need to re-wrap it. eg with $($current) which I do not recommend as a solution to an uninitialised jQuery variable): 您需要将$ current初始化为一个空的jQuery对象,以提供最一致的行为(永远不要将jQuery对象定义为那样使用,否则您需要重新包装它。例如,使用$($current) ,我不这样做建议作为未初始化jQuery变量的解决方案):

var $current = $();   // $() returns an empty jQuery object

Assuming $current is another jQuery object, you can't compare objects like that. 假设$current是另一个jQuery对象,则不能像这样比较对象。 You can however compare their inner values. 但是,您可以比较它们的内部值。 Change: 更改:

$current != $('#planungtext')

To: 至:

$current[0] != $('#planungtext')[0]

If your comparing 2 html input element, you might want to check only the id attribute. 如果比较2 html输入元素,则可能只需要检查id属性。

Since #planungtext is already a unique identifier. 由于#planungtext已经是唯一标识符。

$($current).attr('id') !== 'planungtext'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM