我有一個textarea,它將包含用戶輸入的代碼,我想要獲取該代碼並使用jQuery對其進行掃描以獲取名爲settings的自定義標記中的值,然後將此值添加到一個輸入,用戶可以在不觸及代碼的情況下更改設置標籤內的值。我能夠獲取值並將它們添加到輸入中,但我無法用新值更新代碼。如何使用jQuery更新textarea內的代碼
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;
});
});
這是將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使事情更容易爲你:
http://jsfiddle.net/mabwhf6a/3/
這是一個小的視頻解釋我想要什麼:
http://screencast.com/t/XqggRlQI6
你能多一點清楚這裏的問題是什麼?或者你在哪一部分代碼中遇到問題? –
@SoorajChandran在用戶輸入的代碼中,有兩個設置標籤,我想用用戶在輸入中輸入的新值更改這些標籤的值。 例如,在我放置的代碼中,有兩個值在設置標籤內:「http://lorempixel.com/640/300/」和「on」,當我放置整個代碼並提交時,我得到這兩個值內部輸入。我希望當用戶更改輸入內的值時,它會在主題代碼內發生更改,因此如果他將「http://lorempixel.com/640/300/」更改爲「google.com」,我想在整個代碼中將其替換。我希望你明白,因爲我的英語不好。 –
@SoorajChandran請參閱此視頻(http://screencast.com/t/XqggRlQI6) –