2017-04-13 150 views
1

我有div的「嘿」。這改變爲「你還好嗎?」當我點擊它。但我想爭取更多的文本。我怎樣才能讓這個當我點擊了「你還好嗎」另一個文本出現,等等...在點擊時改變文字並不斷變化

HTML:

$(document).ready(function() { 
 
    $("#fold").click(function() { 
 
     $("#fold_p").text("Are you ok?"); 
 
    }) 
 
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<p><div id="fold"> 
 
    <p id="fold_p">Hey</p> 
 
</div>

此外,是否有可能使最後的文本鏈接?任何幫助深表感謝。 謝謝

+0

你可以在每一次點擊... ** **舉例https://jsfiddle.net/b0vjgny9/ – NewToJS

+1

創建消息數組通過持有一個數組和循環文本。每次單擊時,將數組中的下一條消息放入文本中。 – Barmar

+0

你想讓它無限循環嗎? –

回答

0

我們可以在jQuery以及在JavaScript實現這兩個功能。

  • 單擊上一個顯示的文本時動態文本更改。
  • 最後文本爲紐帶

使用JavaScript

var text = ["First","Second","Third","Fourth"] 
 

 
var index = 0; 
 
document.getElementById("fold").onclick = function() { 
 
    index++; 
 
    if(index < text.length) { 
 
    if(index == text.length-1) { 
 
    document.getElementById("fold_p").innerHTML = '<a href="">'+text[index]+'</a>'; 
 
    } else { 
 
    document.getElementById("fold_p").innerHTML = text[index]; 
 
    } 
 
    } 
 
}
<div id="fold"> 
 
    <p id="fold_p">Hey</p> 
 
</div>

使用jQuery

var text = ["First","Second","Third","Fourth"] 
 

 
var index = 0; 
 
$("#fold").click(function() { 
 
    index++; 
 
    if(index < text.length) { 
 
    if(index == text.length-1) { 
 
    $("#fold_p").html('<a href="">'+text[index]+'</a>'); 
 
    } else { 
 
    $("#fold_p").text(text[index]); 
 
    } 
 
    } 
 
})
<div id="fold"> 
 
    <p id="fold_p">Hey</p> 
 
</div>

+0

謝謝,你真的幫了我。但我仍然對作爲鏈接的最後一個詞感到困惑。 對不起,我很新的HTML和朋友,我用它的工作 –

+0

你問你的問題如何使最後一段文字作爲一個鏈接。所以我也回答了這個問題。 –

+0

是的,我知道。我仍然不知道它是如何工作的。 imake如何轉到外部頁面。 –

2

在這裏,你去!只需創建一個數組就像評論中所述!

var text = ["Hi","One","Two","Three","Four"] 
 

 
$(document).ready(function() { 
 
    var index = 0; 
 
    $("#fold").click(function() { 
 
     index++; 
 
     $("#fold_p").text(text[index]); 
 
    }) 
 
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<p><div id="fold"> 
 
    <p id="fold_p">Hey</p> 
 
</div>

+0

非常感謝您的反饋。我要試試 –

1

我最好使用一個數組,然後以具有不同的導語吐出陣列偏移。

$(document).ready(function() { 
 
    textList = ["Are you okay?", "Well that's cool.", "I like puppies"]; 
 
    $("#fold").click(function() { 
 
    $("#fold_p").text(textList.shift()); 
 
    }) 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<p><div id="fold"> 
 
    <p id="fold_p">Hey</p> 
 
</div>