jquery - 如何使用 jQuery 创建 RedCloth 实时预览?

标签 jquery ruby-on-rails redcloth live-preview

我在使用 Rails 的许多所见即所得 gem/插件时遇到了问题,因此我正在使用 RedCloth gem 自己构建一个。我希望用户在填写表单时看到 HTML 格式文本的实时预览,但不知道如何使用 jQuery 和 RedCloth 来做到这一点。这是我在 application.js 中尝试的内容:

$('#comment').keyup(function(){
  var formatted = RedCloth.new($(this).val()).to_html;
  $('#preview').html(formatted);
});

这不起作用并不奇怪,因为 RedCloth.new 可能无法在 .js 文件中执行,但不知道如何动态格式化文本。

最佳答案

我必须自己处理这个问题。正如 Geoff 和 A​​ndy 提到的,您有 2 个选择:

  1. 使用 JavaScript 解析纺织品并使用 jquery 将其粘贴到您的页面中
  2. 使用 Ajax 调用从服务器获取解析后的纺织品,并使用 jquery 将其粘贴到页面中

我正在使用http://github.com/aaronchi/jrails用 jquery 替换 scriptactulous,这会让事情变得更容易一些。

这就是我所做的:

我决定实现选项 2,因为获得与 RedCloth 中显示的格式完全相同的格式对于我的应用程序至关重要。

我将以下内容添加到 <head> 中我的页面:

<script>
var timeStamp1 = -1;
var timeStampSent1 = -1;
function delay() {
    setTimeout('preview()',1000);
}
function preview() {
    var n = new Date().getTime();
    // Ask for update if textarea was changed since this function last ran
    if (timeStamp1 != -1 && timeStamp1 != timeStampSent1) {
        $.post('/whatevers/ajax_update_preview', $('#textile').serialize(), null, "script");
        timeStampSent1 = timeStamp1;
    }
    delay(); // Run this again in 1000ms
}

// Important for letting you send ajax requests with jquery & rails
jQuery.ajaxSetup({  
    'beforeSend': function (xhr) {xhr.setRequestHeader("Accept", "text/javascript")}  
});


$(document).ready(function(){
    // Event binding to watch for changes to the textarea
    $('#textile').keydown(function() {
      timeStamp1 = event.timeStamp
    });
});
</script>

<body>你显然需要:

<textarea id="textile" name="some_text"></textarea>
<div id="preview"></div>

您的 Controller 中需要以下内容:

class WhateversController < ApplicationController
  def ajax_update_preview
    txt = params[:some_text]
    render :update do |page|
      page.replace_html 'preview', :partial => 'preview', :object => txt
    end
  end

以及部分(_preview.html.haml;它在 HAML 中,因为这就是我使用的,但您也可以在 ERB 中执行此操作,并且您需要在environment.rb 中 gem.config RedCloth gem):

- if live_textile_preview
  = RedCloth.new(live_textile_preview).to_html

最后,记住将其放入你的routes.rb中:

map.resources :whatevers, :collection => {:ajax_update_preview => :post}

我对 javascript 非常缺乏经验(我只是将一些东西混在一起),所以我确信这里的 JS 可以改进。

请注意,如果您有大量并发用户,这会对服务器资源造成重大影响。如果是这种情况,您最好使用 JavaScript 在客户端处理纺织品。

关于jquery - 如何使用 jQuery 创建 RedCloth 实时预览?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3498293/

相关文章:

ruby - 安装 RedCloth 时出错

ruby-on-rails - 红布 2.0.0 [i386-mingw32] 上的 RedCloth 加载错误

ruby - 这个结构在 Ruby 中是什么意思?

javascript - jQuery 元素以某种方式缓存在 setInterval 中

ruby-on-rails - 使用不同的列处理单表继承

css - 使样式表覆盖 Ruby on Rails 应用程序中的所有其他样式表

ruby-on-rails - 在与标准 "production"或 "development"不同的数据库上使用 Rails 迁移

jquery - 我可以为 iPad 指定纵向初始 View 比例和横向初始 View 比例吗?

Javascript条件输入id语句

javascript - 将样式添加到在 jquery 中的 document.ready 之后加载的 div