How do I replace jQueryUI button text?

2019-04-17 19:52发布

I've got a button that I use with jQueryUI somethink like this (simplified).

<button id="mybutton">Play<button>
<script>
$("#mybutton").button().toggle(
    function(){
       $(this).text('Stop');
    },
    function(){
       $(this).text('Start');
    },
);
</script>

This code breaks the way the button looks because when making it into the button widget, there's a new span added inside the button. So I'm changing the button value like this now

$(this).find('span').text('Stop');

This is hacky because I can't treat the button as a black box anymore and have to go inside.

Is there a clean way to do this?

6条回答
贼婆χ
2楼-- · 2019-04-17 19:55

Is the id of the button always myButton? If yes, then just use

$("#myButton").text('Stop');

查看更多
甜甜的少女心
3楼-- · 2019-04-17 20:00

You can use the .button("refresh") method after you alter the text.

$("#mybutton").button().toggle(
    function(){
       $(this).text('Stop').button("refresh");
    },
    function(){
       $(this).text('Start').button("refresh");
    },
);

http://jqueryui.com/demos/button/#method-refresh

查看更多
Animai°情兽
4楼-- · 2019-04-17 20:04

I don't know if you're still looking for an answer to this, but I found your question. If you look at the code from the button, jQuery adds a tag or two. So instead of rewriting the entire thing, I replaced the button .html() with the same html but used javascript search() to switch out the label. It's ugly, but it works. It also uses the button label to switch correctly.

var bdef = $(this).html();
var ht = "";
if (bdef.search("Nuevo") != -1) { 
    ht = $(this).html();
    $(this).html(ht.replace("Nuevo", "Lista"));
}
else {
    ht = $(this).html();
    $(this).html(ht.replace("Lista", "Nuevo"));
}
查看更多
叼着烟拽天下
5楼-- · 2019-04-17 20:10

Maybe you could use the label option of the jQuery UI button now instead?

$("#mybutton").button().toggle(function() {
   $(this).button('option', 'label', 'Stop');
}, function() {
   $(this).button('option', 'label', 'Start');
});

jsbin preview here

查看更多
ゆ 、 Hurt°
6楼-- · 2019-04-17 20:13

after calling .button() to make a jQuery UI button, the text seems to be removed from the original button element and placed in a <span class = ui-button-text></span> within the button element.

Something like this would work:

$("#myButton > .ui-button-text").text("New Text");
查看更多
Anthone
7楼-- · 2019-04-17 20:15

You need to do .button("refresh")

$('#mybutton').text('Save').button("refresh");
查看更多
登录 后发表回答