0

Edit: both if else statements executing. - I have a table with buttons in it. On page load, if the label of the button is 'Hello', I want to change it to something else. I have if-else statement but all the time, both if else statements are being executed. I do not what is wrong here.

 $(document).ready( function() {

   if($('button').val() == "Hello" ) {
      alert("Hello I am in if");
      $(this).removeClass('btn-danger');
      $(this).addClass('btn-primary');
      $(this).text('ifif');
    }
    else {
     alert("Hello I am in else");
     $(this).removeClass('btn-primary');
     $('button').addClass('btn-danger');
     $('button').text('elseelse');
    }
  });

Everytime, the label of the button changes to elseelse even when the initial label of button is 'Hello'. First it goes inside if and changes the label to ifif and then goes inside else too.It works fine if I put it in a click event function. But on page load it does not work correctly.

Your responses will be appreciated.

Thanks

4

3 回答 3

1

您应该使用text()方法,而不是val()获取按钮文本的方法。另外,请注意,这$('button')将选择您页面中的所有按钮,这可能不是您想要的。

$('button').text() == "Hello"

另外,我注意到您$(this)在文档就绪处理程序中使用,这似乎是错误的,因为this不会引用您的按钮。您应该执行以下操作:

$(document.ready(function () {
    var $btn = $('#your_button_id');

    if ($btn.text() === 'Hello') {
        $btn.removeClass('btn-danger');
        //...
    }
});

“其实我希望所有的按钮都被选中。”

根据这些不同的要求,您可以执行以下操作:

http://jsfiddle.net/WpJpV/1/

HTML

<button class="btn-danger">Hello</button>
<button class="btn-danger">Hello</button>
<button class="btn-danger">Hello></button>
<button class="btn-danger">Hello></button>
<button class="btn-primary">Yo</button>

JS

$(function () {
    var classes = 'btn-danger btn-primary';

    $('button:not(:contains(Hello))').toggleClass(classes).text('elseelse');
    $('button:contains(Hello)').toggleClass(classes).text('ifif');

});
于 2013-04-20T05:36:39.220 回答
0

尝试

$(function(){
    $('button').not(':contains(Hello)').removeClass('btn-primary').addClass('btn-danger').text('elseelse');

    $('button:contains(Hello)').removeClass('btn-danger').addClass('btn-primary').text('ifif');
});

演示:小提琴

或者

$(function(){
    $('button').each(function(){
        var $this = $(this);
        if($this.text() == 'Hellow'){
            $this.removeClass('btn-danger').addClass('btn-primary').text('ifif');
        } else {
            $this.removeClass('btn-primary').addClass('btn-danger').text('elseelse');
        }
    })
});

演示:小提琴

于 2013-04-20T05:40:24.900 回答
0

你应该使用.each()函数,演示:http: //jsfiddle.net/UCEAw/1/

$('button').each(function () {
    if ($(this).val() == 'hello') {
        $(this).text('Hello');
    } else {
        $(this).text('World');
    }
});
于 2013-04-20T06:11:37.757 回答