javascript - 为什么我的 JQuery ReplaceWith() 不工作?

标签 javascript php jquery

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

相关文章:

javascript - 随机移动图像

javascript - 我的自动完成功能会忽略我的 JSON 数据并显示随机数

php - 使用 PHP-FFmpeg 创建图像视频缩略图

php - 使用 PHP 获取 Google Analytics 中的特定页面浏览量

javascript - setTimeout 函数不停止执行?

javascript - TypeError : app. get 不是函数

javascript - 回调在 Angular2/Firebase 中生成 "TypeError: this is undefined"

javascript - HTML5 视频当前时间未在 Chrome 中更新

c# - 如何为动态创建的按钮(每个按钮)创建 EventHandler C# VS2010

javascript - jQuery 测试表单字段是否不为空