为什么我的JQuery replaceWith()不能工作?

Why Isn't My JQuery replaceWith() Working?

本文关键字:不能 工作 我的 JQuery replaceWith 为什么      更新时间:2023-09-26

我正在努力完成一项看似简单的任务。我想用一个新的随机推荐按钮点击取代显示的推荐。我使用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'); 
});

尝试使用htmltext

演示:

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>

另外,检查控制台是否有错误。它可能告诉你比你所展示的更多的东西。