如何通过jQuery使用replace方法更新textarea

时间:2015-08-25 18:34:40

标签: javascript jquery html css xml

我有一个textarea,它将包含用户输入的代码,我想获取该代码并使用jQuery扫描它以获取名为settings的自定义标记内的值,然后将此值添加到输入中,以便用户能够更改设置标记内的值而不触及代码。我能够获取值并将它们添加到输入中,但我无法使用新值更新代码。

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代码:

.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并复制上面的代码,然后将其放入textarea并单击提交代码,您将获得两个输入,这些输入的内容来自这两个标记:

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

我希望当用户更改输入值并单击“更新代码”以更改整个代码中设置标记的值。

2 个答案:

答案 0 :(得分:2)

试试这个,看看它是否适合您:

<强> HTML

<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中找到并提取设置标签(我认为是沮丧和肮脏的。)。

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

编辑:更新了包含贫民窟包装功能的答案,以阐明这一概念。我不建议按原样使用它,而是使用真正的模板,这需要超出此问题范围的工作。

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

答案 1 :(得分:1)

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

脚本:

/*======= Container =======*/

#container {
  display: flex;
  flex-direction: row;
  min-height: 100vh;
}
#content-wrap {
  width: 100%;
}
/*======= Sāna izvēlne / header =======*/

header {
  min-height: 100vh;
  width: 150px;
  margin: 0;
  background-color: red;
  flex: 0 0 150px;
}
.header-position {
  width: inherit;
  height: 100vh;
  position: fixed;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}
nav {
  background-color: #ffffff;
}
nav ul {
  padding: 0;
  margin: 0;
}
nav li,
a {
  text-decoration: none;
  list-style-type: none;
  text-align: right;
  font-size: 1em;
  color: black;
}
.logo {
  background: url("../images/AG.svg");
  background-size: contain;
  background-repeat: no-repeat;
  width: 80px;
}
/*======= Banneris =======*/

.banner-container {
  background-image: url("../images/lp-background.jpg");
  background-size: cover;
  background-repeat: no-repeat;
  width: 100%;
  height: 300px;
  clear: right;
}
.banner {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
}
.banner h1 {
  color: white;
  font-family: 'Roboto', sans-serif;
  text-transform: uppercase;
  font-weight: bold;
  letter-spacing: 0.4em;
  border: solid 10px white;
  padding: 20px 30px;
}
/*======= Par mums =======*/

#about {
  width: 100%;
  height: 300px;
  background-color: pink;
}
#about .first,
.second {
  width: 50%;
  height: 100%;
  display: inline-block;
}
#about .first {} #about .second {
  float: right;
}
.about-picture {
  height: 200px;
  width: 200px;
  margin: 50px 50px;
  border-radius: 150px;
  border: solid 4px rgb(246, 243, 199);
}
.about-picture.right {
  float: right;
}
img.right {
  float: right;
}

HTML模板:

<div id="container">
  <header>
    <div class="header-position">
      <img class="logo" src="./images/AG.svg" alt="AG Logo"></img>

      <nav>
        <ul>
          <li><a href="#">Sākums</a>
          </li>
          <li><a href="#">Attēli</a>
          </li>
          <li><a href="#">Kontakti</a>
          </li>
          <li><a href="#">Par mums</a>
          </li>
        </ul>
      </nav>
      <a href="mailto:">Sazinies ar mums</a>
    </div>
  </header>

  <div id="content-wrap">

    <div class="banner-container">

      <span class="banner"><h1>Whatever</h1></span>

    </div>

    <div id="about">
      <div class="first">
        <img class="about-picture left" src="./images/lp-background.jpg" alt="" />

      </div>
      <div class="second">
        <img class="about-picture right" src="./images/lp-background.jpg" alt="" />

      </div>
    </div>

  </div>

我无法替换&#39; on&#39;在你提供的模板中,不确定它是否与某些保留关键字有关,但其他一切都正常。