最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Click on a button to change multiple span items - Stack Overflow

programmeradmin4浏览0评论

Let's say I have multiple span items such as

<span>A</span>
<span>B</span>
<span>C</span>
<span>D</span>

and a div (which I will change to a button later) called "change".

<div id="change">CHANGE</div>

Is there a way to change the text of all the span items on the page with a single button click?

I'm not very familiar with JavaScript and so far, I'm trying this code but it doesn't seem to work.

$(document).ready(function(){
    $('#change').click(function(){
        $("span").replaceAll(function(){
            while ('span') {
                if ($('#span').text() == 'A') {
                    return $('span').text('B');
                }
                else if ($('span').text() == 'B') {
                    $('span').text('C');
                }
                else if ($('span').text() == 'C') {
                    $('span').text('D');
                }
                else if ($('span').text() == 'D') {
                    $('span').text('A');
                }
            }
        });
    });
});

Thanks in advance!

Let's say I have multiple span items such as

<span>A</span>
<span>B</span>
<span>C</span>
<span>D</span>

and a div (which I will change to a button later) called "change".

<div id="change">CHANGE</div>

Is there a way to change the text of all the span items on the page with a single button click?

I'm not very familiar with JavaScript and so far, I'm trying this code but it doesn't seem to work.

$(document).ready(function(){
    $('#change').click(function(){
        $("span").replaceAll(function(){
            while ('span') {
                if ($('#span').text() == 'A') {
                    return $('span').text('B');
                }
                else if ($('span').text() == 'B') {
                    $('span').text('C');
                }
                else if ($('span').text() == 'C') {
                    $('span').text('D');
                }
                else if ($('span').text() == 'D') {
                    $('span').text('A');
                }
            }
        });
    });
});

Thanks in advance!

Share Improve this question edited Apr 22, 2016 at 9:46 J. Hong asked Apr 22, 2016 at 9:38 J. HongJ. Hong 314 bronze badges 2
  • like this jsfiddle/LeoLion/d4ewwqm5 – Leo the lion Commented Apr 22, 2016 at 9:44
  • 1 Do you want to change each span text individually or change all of the texts to the same text ? – Aurel Commented Apr 22, 2016 at 9:46
Add a ment  | 

10 Answers 10

Reset to default 3

Simple example: altering the content from the text() callback:

$("#change").on("click",function() {
 $("span").text(function(i,txt) {
   return {
     "A":"B",
     "B":"C",
     "C":"D",
     "D":"A"
   }[txt];
 });
});
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<span>A</span>
<span>B</span>
<span>C</span>
<span>D</span>
<button id="change">CHANGE</button>

IF your span elements are grouped you could use .append() to parent:

$("#change").on("click", function(){
  $("#spans").append( $("#spans span").eq(0) )
});
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="spans">
  <span>A</span>
  <span>B</span>
  <span>C</span>
  <span>D</span>
</div>
<button id="change">CHANGE</button>

If your SPANS are not grouped (irrelevant position in DOM), but rather share a same className you could:

  • map your <span>s content into array of contents
  • modify the array
  • finally send the modified array to each SPAN

var spans = $(".spn");

// Map spans content into Array
var conts = spans.map(function(){
  return this.innerHTML;
}).get();


$("#change").on("click", function(){
  
  // Modify the Array first

  // DIRECTION >>>
  // conts.unshift(conts.pop());

  // DIRECTION <<<
  conts.push(conts.shift());

  // Than send the array values to spans
  spans.text(function(i){
    return conts[i];
  });

});
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<span class="spn">A</span>
<span class="spn">B</span>
<span class="spn">C</span>
<span class="spn">D</span>
<button id="change">CHANGE</button>

Yes, in all examples you can click and perform the switch as many times you want!
If you don't want that, than instead of .on( use .one(

Well, if you just wants to change span text on click conditionally you can loop all span by using JQuery each() Method:

HTML:

<span>A</span>
<span>B</span>
<span>C</span>
<span>D</span>
<br><br><br>
<div id="change">CHANGE</div>

JQuery:

$(document).ready(function(){
    $('#change').click(function(){
            $("span").each(function(){

                if ($(this).text() == 'A') {
                    return $(this).text('B');
                }
                else if ($(this).text() == 'B') {
                    $(this).text('C');
                }
                else if ($(this).text() == 'C') {
                    $(this).text('D');
                }
                else if ($(this).text() == 'D') {
                    $(this).text('A');
                }            
        });        
    });
});

DEMO: http://jsfiddle/xpadzam8/

Yes you can do that easily, for example with jquery your click can be catch with :

$("#change").on("click",function(){
 $("span").text(function(i,txt){
    switch(txt){
       case "A" : $(this).text("B"); break;
       case "B" : $(this).text("C"); break;
       case "C" : $(this).text("D"); break;
       case "D" : $(this).text("A"); break;
    }
 });
});

If you look at the documentation, you will see that your usage of replaceAll() is incorrect.

Use repalceWith.

Also, since you want to replace all the spans with one click, get rid of the if-else.

Well, i made some changes in your code, you can have a look on JSFiddle

$('#changeText').click(function(){
    $("span").text("my text");
});

According to your code what you need is .each() and $(this).html(); function.

UPDATED CODE

$('#change').click(function(){
 $('span').each(function(){
   if ($(this).html() == 'A') {
     $(this).html('B');
   }
   else if ($(this).html() == 'B') {
     $(this).html('C');
   }
   else if ($(this).html() == 'C') {
     $(this).html('D');
   }
   else if ($(this).html() == 'D') {
     $(this).html('A');
   }
 });
});

Updated fiddle

maybe you can do:

$(document).ready(function(){
        $(document).ready(function(){
        $('#change').click(function(){
            $('span').each(function(){
                var txt=$(this).text();
                switch (txt){
                    case 'A': $(this).text('B');break;
                    case 'B': $(this).text('C');break;
                    case 'C': $(this).text('D');break;
                    case 'D': $(this).text('A');break;

                }
            })
        });
    });

try this hack

 $('#change').click(function(){
        var f = $("span").first();
        var c = f.detach();
        var l = $("span").last();
        c.insertAfter(l)

    });

$('#change').click(function() {
  var f = $("span").first();
  var c = f.detach();
  var l = $("span").last();
  c.insertAfter(l)

});
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="spans">
  <span>A</span>
  <span>B</span>
  <span>C</span>
  <span>D</span>
</div>
<button id="change">CHANGE</button>

$('#changeButton').click(function (event) {
    var _changeMap = {
        A: 'B',
        B: 'C',
        C: 'D',
        D: 'E',
    };

    $('span').each(function (index, element) {
        element.innterText = _changeMap[element.innerText.trim()];
    });

    $.preventDefault();
});

Your question is not very clear.If you want to change the text of all spans with the same text you can just select all spans.Like this :

$(document).ready(function(){
    $('#change').click(function(){
    $("span").text('your text');
    });
 });

If you want to change each span individually with a custom text (in your code you seem to replace the text of each span with the text of the next span, except for the last one which takes the text of the first one) you should iterate through spans with .each() .That would work no matter where the spans are located in page.In case you want to select only spans with a certain class just replace span with span.yourclass.Something like this:

$(document).ready(function(){
    $('#change').click(function(){

    var first=$("span").first().text(); //store the text of the first span

    $("span").not(':last').each(function(){ //select all spans except last
    $(this).text($(this).next('span').text()); //change text of each span to text of next span
    });

    $("span").last().text(first);   //set the text of the last span to the text of the first 
    });
 });

https://jsfiddle/fdkxu2dc/1/

发布评论

评论列表(0)

  1. 暂无评论