简体   繁体   English

如果else语句不起作用,则jQuery addClass和removeClass

[英]jQuery addClass and removeClass in if else statement not working

So I have created a class with a border. 所以我创建了一个带有边框的类。 called border-check. 称为边界检查。 This border only needs to show when the td.k-editable-area has no value (nothing written in the textarea). 仅当td.k可编辑区域没有值(文本区域中未写入任何内容)时,才需要显示此边框。

I can add a class with the first line but once I add the if else statement it breaks down and wont add the class. 我可以在第一行添加一个类,但是一旦添加if else语句,它就会崩溃,并且不会添加该类。 So I'm not sure if its a problem of adding the class again or wether my if else statement is not correctly stated. 所以我不确定是否是再次添加该类的问题还是我的if else语句未正确说明。

$("td.k-editable-area").addClass("border-check");

if ("td.k-editable-area" == "") {
    $("td.k-editable-area").addClass("border-check");
} else {
    $("td.k-editable-area").removeClass("border-check");
}

Your if statement is comparing two different strings. 您的if语句正在比较两个不同的字符串。

"td.k-editable-area" == "" //false

It is not taking value from the element $("td.k-editable-area") , so make it 它不是从元素$("td.k-editable-area") ,因此使其

if ( $("td.k-editable-area").text().trim() == "") {

Edit 编辑

If this has to be checked for multiple td s then 如果必须检查多个td

$("td.k-editable-area").each( function(){
   var $this = $(this);
   if ( $this.text().trim() == "") {
      $this.addClass("border-check");
   } else {
      $this.removeClass("border-check");
   }
})

As the others have said, your condition is testing two strings, which isn't what you want. 正如其他人所说,您的条件是测试两个字符串,这不是您想要的。

If your goal is to add/remove the class on each of those td s based on whether that specific one is empty, you'll need a loop: 如果您的目标是根据特定的td是否为空在每个 td上添加/删除该类,则需要一个循环:

$("td.k-editable-area").each(function() {
    var $this = $(this);
    $this.toggleClass("border-check", !$this.text().trim());
});

You can't just use 你不能只用

// NOT THIS
$("td.k-editable-area").toggleClass("border-check", !$("td.k-editable-area").text().trim());

...because that will update the class on all elements based on whether they're all blank. ......因为这将更新基于它们是否都是空白的所有元素的类。 (With any other jQuery accessor, it would be based on the first one, but text is weird.) (对于任何其他jQuery访问器,它都将基于第一个访问器,但是text很奇怪。)

OP here, I have ended up finding the answer with your help. OP,在您的帮助下,我终于找到了答案。 Thanks you! 谢谢! The correct code was: 正确的代码是:

 function onEditorChange(e) {
            var text = e.sender.body.innerText;

            if (text.trim() === "") {
                $("td.k-editable-area").addClass("border-check");
            } else {
                $("td.k-editable-area").removeClass("border-check");
            } 
        }

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

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