简体   繁体   English

使用三元运算符切换按钮文本

[英]Toggling button text using ternary operator

I am trying to toggle button text by using ternary operator but it is not working.我正在尝试使用三元运算符切换按钮文本,但它不起作用。

<button type="button" id="ter" >Bar</button>

$("#ter").click(function(){
   $(this).text() = 'Bar' ? 'column':'Bar';
});

Is this possible to do this way?可以这样做吗? and what part I am doing wrong?我做错了什么? I know there many other ways to achieve this but I just need to know if it is possible in this method or not?我知道有很多其他方法可以实现这一点,但我只需要知道这种方法是否可行?

You could also try this:你也可以试试这个:

$("#ter").click(function(){
    var newText = ($(this).text() == 'Bar') ? 'column':'Bar';
    $(this).text(newText);
});

This checks if the current text is equal to 'Bar' with $(this).text() == 'Bar' .这用$(this).text() == 'Bar'检查当前文本是否等于$(this).text() == 'Bar' If it is, it sets the variable newText to 'column' (or vice versa).如果是,它将变量 newText 设置为 'column'(反之亦然)。 The second line replaces the old text with the new text.第二行用新文本替换旧文本。

You are using the ternary operator wrong.您错误地使用了三元运算符。 It goes:它是:

[statement] ? [code when true] : [code when false]

You're basically testing if('Bar') right now which will always return true.您现在基本上是在测试if('Bar')它将始终返回 true。

You're doing it wrong, you could instead use this approach:你做错了,你可以改用这种方法:

$("#ter").click(function(){
   $(this).text(function (i, t) {
       return t === 'Bar' ? 'column':'Bar';
   });
});

The reason it didn't work is because:它不起作用的原因是:

  1. You were trying to assign a result to $(this).text() (using = ) instead of comparing ( == or === ), and您试图结果分配$(this).text() (使用= )而不是比较===== ),并且
  2. Not returning anything to update the text不返回任何内容来更新文本

It's important to note that with jQuery the text() method (and most others) when called with no arguments is a getter (it gets the current value), but to use it as a setter you have to pass an argument, either directly ( $(this).text('foo') ) or using the anonymous function ( $(this).text(function(){ return 'foo'; }) ).重要的是要注意,使用 jQuery, text()方法(和大多数其他方法)在不带参数的情况下调用时是一个getter (它获取当前值),但是要将它用作setter,您必须直接传递一个参数( $(this).text('foo') ) 或使用匿名函数( $(this).text(function(){ return 'foo'; }) )。 Calling the getter, and comparing that retrieved value (or trying to assign to it) does not act as a setter.调用 getter 并比较检索到的值(或尝试分配给它)不会充当 setter。

In the anonymous functions available to jQuery methods, the first argument (here called i , but the name is irrelevant, it's always the first argument) is the index of the current ' $(this) ' object in the collection returned by jQuery, the second argument (here called t , but again the name is irrelevant) represents the current (pre-manipulation) value found by the method.在 jQuery 方法可用的匿名函数中,第一个参数(这里称为i ,但名称无关紧要,它始终是第一个参数)是 jQuery 返回的集合中当前“ $(this) ”对象的索引,第二个参数(此处称为t ,但名称同样无关紧要)表示该方法找到的当前(操作前)值。

References:参考:

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

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