我正在尝试完成一项看似简单的任务。我想在单击按钮时将显示的推荐替换为新的随机推荐。我正在使用 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');
});
关于javascript - 为什么我的 JQuery ReplaceWith() 不工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32379340/