我正在尝试完成看似简单的任务。我想在单击按钮时用新的随机推荐替换显示的推荐。我正在使用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');
});

10-07 14:09