[英]Why Isn't My JQuery replaceWith() Working?
我正在嘗試完成一個看似簡單的任務。 我要在按鈕單擊時用新的隨機推薦替換顯示的推薦。 我正在使用JQuery和PHP。 不幸的是,當我單擊按鈕時,絕對沒有任何反應。 這是我的代碼:
<div id="home-slogan">
<?php
$filename = "testimonials/testimonial.txt"; #specify file
$file = fopen($filename, "r"); #open file
$numLines = count(file($filename)); #count number of lines
$lines = file($filename); #read lines into array
$randomTestimonial = rand(0,$numLines); #generate random number
?>
<h1 id="heading" align="center">"<?php echo $lines[$randomTestimonial];?>"</h1>
<button type="button" id="next">Next Testimonial</button>
<script>
var randomTestimonial = <?php echo $lines[$randomTestimonial];?>;
$("#next").click(function(){
$("#heading").replaceWith(randomTestimonial);
});
</script>
有任何想法嗎? 謝謝!!!
您可能正在生成語法錯誤(在Windows上使用F12打開控制台),因為未對字符串加引號。
var randomTestimonial = '<?php echo addslashes($lines[$randomTestimonial]); ?>';
至於更改標題中的文本,您可能想要做更多類似的事情。
$('#next').click(function() {
// Since right now randomTestimonial isn't regenerating
$('#heading').text('Random text');
});
嘗試使用html
或text
。
演示: http : //jsfiddle.net/8cvtxjt6/
<h1 id="heading" align="center">"test is best"</h1>
<button type="button" id="next">Next Testimonial</button>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript" src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
<script>
var randomTestimonial = "glue";
$("#next").click(function(){
$("#heading").html('"'+randomTestimonial+'"');
});
</script>
另外,請檢查您的控制台是否有錯誤。 它可能會告訴您比所顯示的更多的信息。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.