【发布时间】:2015-08-26 21:35:26
【问题描述】:
我有一个文本区域,其中包含用户输入的代码,我想获取该代码并使用 jQuery 扫描它以获取名为 setting 的自定义标记内的值,然后将此值添加到输入中,以便用户能够在不接触代码的情况下更改设置标签内的值。我能够获取这些值并将它们添加到输入中,但我无法使用新值更新代码。
HTML 代码:
<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 代码:
$('#template-code').change(function (){
var $that = $(this),
template_code = $that.val(),
code = '',
new_data = '';
// 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 ) {
template_code += $(template_code).find('setting#'+ new_field.name).text(new_field.value);
console.log(new_field.value);
});
$('#template-code').val(template_code);
$('#tab-1').removeClass('unactive');
return false;
});
});
这是一个将添加到文本区域内的主题代码示例:
<?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,可以让您更轻松:
http://jsfiddle.net/mabwhf6a/3/
这是一个解释我想要什么的小视频:
【问题讨论】:
-
您能否更清楚地说明这里的问题是什么?或者您对代码的哪一部分有疑问?
-
@SoorajChandran 在用户输入的代码中有两个设置标签,我想用用户在输入中输入的新值更改这些标签的值。例如,在我输入的代码中,设置标签中有两个值,它们是:“lorempixel.com/640/300”和“on”,当我输入整个代码并提交它时,我在输入中得到这两个值。我希望当用户更改输入中的值时,它会在主题代码中更改,因此如果他将“lorempixel.com/640/300”更改为“google.com”,我想在整个代码中替换它。我希望你能理解,因为我的英语不好。
-
@SoorajChandran 请看这个video
-
演示中的代码与所讨论的不同。请更新问题和代码以明确和相关
-
@charlietfl 你是什么意思?请看这个:screencast.com/t/XqggRlQI6
标签: javascript jquery html css xml