简体   繁体   中英

Why Isn't My JQuery replaceWith() Working?

I'm trying to accomplish a seemingly simple task. I want to replace the displayed testimonial with a new random testimonial on button click. I'm using JQuery and PHP. Unfortunately, absolutely nothing happens when I click the button. Here is my code:

<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>       

Any ideas? Thanks!!!

You're probably generating a syntax error (opening your console with F12 on Windows) because your string isn't quoted.

var randomTestimonial = '<?php echo addslashes($lines[$randomTestimonial]); ?>';

As for changing the text in the header, you probably want to do something more like this.

$('#next').click(function() {
  // Since right now randomTestimonial isn't regenerating
  $('#heading').text('Random text'); 
});

Try using html or text .

Demo: 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>

Also, check your console for errors. It may tell you something more than what you have shown.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM