如何通过jQuery使用replace方法更新文本区域

How to update textarea with replace method through jQuery

本文关键字:更新 文本 区域 方法 replace 何通过 jQuery 使用      更新时间:2023-09-26

我有一个文本区,将包含由用户输入的代码,我想获得该代码,并扫描它与jQuery,以获得一个自定义标签内的值称为设置,然后将此值添加到输入,这样用户将能够改变设置标签内的值,而不触及代码。我能够获得值并将它们添加到输入中,但我无法用新值更新代码。

HTML CODE:

<div id='tab-1'>
  <textarea id='template-code' cols='67' rows='27'></textarea>
  <button id='submit-code'>Submit Code</button>
</div>
<div id='tab-2' class='unactive'>
  <form id='settings-form' method='POST'>
    <div id='result'></div>
    <button id='update-code'>Update Code</button>
  </form>
</div>
CSS CODE:

.unactive {
    display: none
}
jQuery CODE:

$('#template-code').change(function (){
  var $that = $(this),
      template_code = $that.val(),
      code = '',
      new_data = '',
      text = '',
      newCode = '';
  // Extract settings from the theme and add them to #result              
  $(document).on('click', '#submit-code', function (){
      $('#tab-1').addClass('unactive');
      $('#tab-2').removeClass('unactive');
      $(template_code).find('setting').each(function (i){
        var $this = $(this),
            setting_std = $this.text(),
            setting_id = $this.attr('id');
        code += '<input id="'+setting_id+'" name="'+setting_id+'" type="text" value="'+setting_std+'"><br>';
      });
      if(code !== ''){
        $('#result').html(code);
      }
  });
  // Update old data with the new one
  $(document).on('click', '#update-code', function (){
    new_data = $( "#settings-form" ).serializeArray();
    $.each( new_data, function( i, new_field ) {
        var start_key = "id='"+new_field.name+"'>",
            end_key = '</setting>',
            start  = template_code.indexOf(start_key), 
            end = template_code.indexOf(end_key);
        text = template_code.substring(start + start_key.length, end);
        // THE PROBLEM IS HERE
        // I want the variable template_code to contains the new value not the old one so I used replace but it seems that it doesn't work
        template_code.replace(text, new_field.value);

    });
    $('#template-code').val(template_code);
    $('#tab-1').removeClass('unactive');
    return false;
  });
});

这是一个主题代码的例子,将被添加到textarea中:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html>
<html b:version='2' class='v2' expr:dir='data:blog.languageDirection' xmlns='http://www.w3.org/1999/xhtml' xmlns:b='http://www.google.com/2005/gml/b' xmlns:data='http://www.google.com/2005/gml/data' xmlns:expr='http://www.google.com/2005/gml/expr'>
  <head>
    <b:include data='blog' name='all-head-content'/>
    <link href='http://fonts.googleapis.com/css?family=Open+Sans+Condensed:300,300italic,700' rel='stylesheet' type='text/css'/>
    <link href='http://fonts.googleapis.com/css?family=Lora:400,400italic,700,700italic' rel='stylesheet' type='text/css'/>
    <link href='https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css' rel='stylesheet'/>
    <title><data:blog.pageTitle/></title>
    <div id='option-panel' style='display:none!important'>
      <setting id='post_thumbnail'>http://lorempixel.com/640/300/</setting>
      <setting id='search_icon'>on</setting>
    </div>
</head>
<body>
</body>
</html>

为了理解我的问题,请进入这个JsFiddle并复制上面的代码,然后把它放在文本区,然后点击提交代码,你会得到两个输入,这些输入的内容来自这两个标签:

<setting id='post_thumbnail'>http://lorempixel.com/640/300/</setting>
<setting id='search_icon'>on</setting>

我想当用户改变输入的值时,点击"更新代码"来改变整个代码中设置标签的值。

试试这个,看看它是不是你想要的:

<div id='tab-1'>
  <textarea id='template' cols='67' rows='27'></textarea>
  <button id='submit'>Submit Code</button>
</div>
<div id='tab-2'>
  <form id='settings-form' method='POST'>
    <div id='result'></div>
    <button id='update'>Update Code</button>
  </form>
</div>
JavaScript:

function wrap(data) {
  var string = '';
  var i, l;
  string += "<?xml version='"1.0'" encoding='"UTF-8'" ?>'r'n";
  string += "<!DOCTYPE html>'r'n";
  string += "<html b:version='2' class='v2' expr:dir='data:blog.languageDirection' xmlns='http://www.w3.org/1999/xhtml' xmlns:b='http://www.google.com/2005/gml/b' xmlns:data='http://www.google.com/2005/gml/data' xmlns:expr='http://www.google.com/2005/gml/expr'>'r'n";
  string += "  <head>'r'n";
  string += "    <b:include data='blog' name='all-head-content'/>'r'n";
  string += "    <link href='http://fonts.googleapis.com/css?family=Open+Sans+Condensed:300,300italic,700' rel='stylesheet' type='text/css'/>'r'n";
  string += "    <link href='http://fonts.googleapis.com/css?family=Lora:400,400italic,700,700italic' rel='stylesheet' type='text/css'/>'r'n";
  string += "    <link href='https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css' rel='stylesheet'/>'r'n";
  string += "    <title><data:blog.pageTitle/></title>'r'n";
  string += "  </head>'r'n";
  string += "  <body>'r'n";
  string += "    <div id='option-panel' style='display:none!important'>'r'n";
  for (i = 0, l = data.length; i < l; i++)
    string += "      " + data[i].toString() + "'r'n";
  string += "    </div>'r'n";
  string += "  </body>'r'n";
  string += "</html>'r'n";
  return string;
}
$("#submit").on('click', function() {
  var virtual = document.createElement("div");
  var temp = '';
  virtual.innerHTML = $("#template").val();
  $(virtual).find('setting').each(function(i) {
    var $this = $(this),
            setting_std = $this.text(),
            setting_id = $this.attr('id');
    temp += '<input id="' + setting_id + '" name="' + setting_id + '" type="text" value="' + setting_std + '"><br>';
  });
  if (temp !== '')
    $('#result').html(temp);
});
$("#update").on('click', function(event) {
  var temp = [];
  event.preventDefault();
  $("#result").find("input").each(function() {
    temp.push("<setting id='"" + this.id.toString() + "'">" + this.value.toString() + "</setting>");
  });
  $("#template").val(wrap(temp));
});

我相信这就是你想要的?尽管您使用的是jQuery,但我认为您最终还是让它变得比原本更加困难。我使用一个虚拟节点来快速/轻松地找到textarea并在提交时只拉出设置标签(我想是向下和脏的吧?)。

我删除了样式和诸如此类的东西,因为它干扰了快速测试,并且您需要对用户输入应用适当的完整性检查/验证。

Edit:更新的答案包括一个ghetto包装函数来阐明概念。我不建议按原样使用它,而是使用一个真正的模板,这将需要超出这个问题范围的工作。

最近编辑后的JSFiddle: http://jsfiddle.net/zo3hh2ye/6/

这是代码的另一个版本。我将新值保存在一个数组中,然后用textarea文本中的现有值替换它们。试一试,看看能不能解决你的问题。

Script:

 <script type="text/javascript">
    $('#template-code').change(function () {
        var $that = $(this),
            template_code = $that.val(),
            code = '',
            new_data = '',
            text = '',
            newCode = '';
        // Extract settings from the theme and add them to #result              
        $('#submit-code').click(function () {
            $('#tab-1').addClass('unactive');
            $('#tab-2').removeClass('unactive');
            $(template_code).find('setting').each(function (i) {
                var $this = $(this),
                    setting_std = $this.text(),
                    setting_id = $this.attr('id');
                code += '<input id="' + setting_id + '" name="' + setting_id + '" type="text" value="' + setting_std + '"><br>';
            });
            if (code !== '') {
                $('#result').html(code);
            }
        });
        // Update old data with the new one
        $('#update-code').click(function () {
            new_data = $("#settings-form").serializeArray();
            $(template_code).find('setting').each(function (i) {
                template_code = template_code.replace("<setting", "").replace("id='" + $(this).attr("id") + "'>", "").replace($(this).html(), "{" + i + "}").replace("</setting>", "");
            });
            $.each(new_data, function (i, new_field) {
                    template_code = template_code.replace("{" + i + "}", "<setting id='" + new_field.name + "'>" + new_field.value + "</setting>");
            });
            $('#template-code').val(template_code);
            $('#tab-1').removeClass('unactive');
            return false;
        });
    });
</script>
模板:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html>
<html b:version='2' class='v2' expr:dir='data:blog.languageDirection' xmlns='http://www.w3.org/1999/xhtml' xmlns:b='http://www.google.com/2005/gml/b' xmlns:data='http://www.google.com/2005/gml/data' xmlns:expr='http://www.google.com/2005/gml/expr'>
  <head>
    <b:include data='blog' name='all-head-content'/>
    <link href='http://fonts.googleapis.com/css?family=Open+Sans+Condensed:300,300italic,700' rel='stylesheet' type='text/css'/>
    <link href='http://fonts.googleapis.com/css?family=Lora:400,400italic,700,700italic' rel='stylesheet' type='text/css'/>
    <link href='https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css' rel='stylesheet'/>
    <title><data:blog.pageTitle/></title>
    <div id='option-panel' style='display:none!important'>
      <setting id='post_thumbnail'>text1</setting>
      <setting id='search_icon'>text2</setting>
    </div>
</head>
<body>
</body>
</html>

我无法在你提供的模板中替换文本'on',不确定它是否与一些保留的关键字有关,但其他一切都很好