我正在使用 ajax 和 codeigniter 来提交我的问题的预览。
但我正在尝试替换 \n
与 <br />
仅在 pre
之前的所有新行上并在每个pre
之后标签。
问题:如何确保它替换 \n
仅在每个前置标记之前和之后的行上使用 `br?
<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>
Controller
<?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);
}
}
最佳答案
我不知道是否有一种简单的方法可以在不解析的情况下做到这一点。假设您不想解析,我认为最简单的解决方案是将 CSS 规则应用于输入问题,就像它是 PRE 元素一样。
#preview{
white-space: pre;
}
关于javascript - 仅在每个前置标记之前和之后的所有新行上将\n 替换为 <br/>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40315979/