我正在使用带有codeigniter的ajax来提交我的问题的预览。
但我尝试仅在\n
之前和每个<br />
代码之后的所有新行上将pre
替换为pre
。
问题:如何确保仅在每个预标记之前和之后的行上用{br}替换\n
?
<script type="text/javascript">
$('#preview-question').on('click', function (e) {
$.ajax({
url: "<?php echo base_url('question/preview');?>",
type: 'POST',
data: {
title: $('#title').val(),
question: $('#question').val(),
'<?php echo $this->security->get_csrf_token_name(); ?>' : '<?php echo $this->security->get_csrf_hash(); ?>'
},
dataType: 'json',
success: function(response){
if (response.success) {
$('#preview').html(response.question.replace(/\n/g, "<br />").before('pre').after('pre'));
var htmlBRCleaned = $('#preview pre').html().replace(/<br\s?\/?>/, '').replace('<br\/>', '').replace(/</g, "<").replace(/>/g, ">");
$('#preview pre').html(htmlBRCleaned);
} else {
}
}
});
e.preventDefault();
});
</script>
控制器
<?php
class Question extends MY_Controller {
public $data = array();
public function __construct() {
parent::__construct();
}
public function index() {
}
public function create() {
$this->form_validation->set_rules('title', 'title', 'trim|required');
$this->form_validation->set_rules('question', 'question', 'trim|required|callback_question');
if ($this->form_validation->run() == true) {
}
$data['page'] = 'question/create';
$this->load->view($this->config->item('config_template') . '/template/template_view', $data);
}
public function question() {
if (empty($this->input->post('question'))) {
$this->form_validation->set_message('question', 'You have not asked a question');
return false;
} else {
return true;
}
}
public function preview() {
$data = array('success' => false, 'question' => '');
if ($_POST) {
$question = $this->input->post('question');
$data['question'] = $question;
$data['success'] = true;
}
echo json_encode($data);
}
}
答案 0 :(得分:1)
我不知道在没有解析的情况下是否有一种简单的方法可以做到这一点。假设您不想解析,我认为最简单的解决方案是对入口问题应用CSS规则,就像它是一个PRE元素。
#preview{
white-space: pre;
}
答案 1 :(得分:0)
在您的上下文中将此replace(/\n/g, "<br />");
更改为此replace(/\\n/ig,'<br/>');
// i flag stands for case insensitve
这是一个简单的演示:
$(document).ready(function(){
var template = $.trim($('#toReplace').html());
//console.log(template);
var replaced = template.replace(/\\n/ig,'<br/>');
console.log(replaced);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<div id="toReplace">
<span>hello world \n</span>
<span>hello world \n</span>
<span>hello world \n</span>
<span>hello world \n</span>
</div>