[英]Jquery function to change html tags
我有一個HTML頁面,包含2個textarea
,一個Input和一個Output。 在輸入textarea
中將輸入以下HTML結構:
<table>
<tr>
<td>TEXT: <input type="text" value="" /></td>
</tr>
<tr>
<td>TEXT: <input type="text" value="" /></td>
</tr>
<tr>
<td>TEXT: <input type="text" value="" /></td>
</tr>
</table>
通過單擊提交按鈕,它會在輸出textarea中為此結構轉換此共振峰:
<ul>
<li>
<label>TEXT:<label>
<input type="text" value="" />
</li>
<li>
<label>TEXT:<label>
<input type="text" value="" />
</li>
<li>
<label>TEXT:<label>
<input type="text" value="" />
</li>
</ul>
即jQuery函數應該:
<UL>
替換<TABLE>
<UL>
<LI>
替換<TD>
<LI>
<TR>
<LABEL>
標記單詞“TEXT” 我的HTML代碼如下所示:
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>Beta style</title>
<script type='text/javascript' src='http://code.jquery.com/jquery-1.8.3.js'></script>
<script>
function gerador() {
var code = $('textarea[name=message]').val(); //Pega código do input
alert(code);
//$("body").append("<h2>Output</h2><textarea id="output" rows="10" cols="100"></textarea>");//Cria campo Output
$('#output').val(code); //Escreve codigo no Output
$('#output:contains("TEXT")').wrapInner('<label> <label / >');
}
</script>
</head>
<body>
<h2>Input</h2>
<textarea name="message" id="input" rows="10" cols="100"></textarea>
<input type="button" value="Submit" onclick="gerador();" />
</body>
</html>
我無法在textarea
添加標簽。
簡單的方法是在td
元素上使用contents
:
var table = $("table"); // Limit this as appropriate
var ul = $("<ul>");
table.find("td").each(function() {
ul.append($("<li>").append($("<label>").append($(this).contents())));
});
table.replaceWith(ul);
那是做什么的:
獲取合適的表(我剛剛使用$("table")
,但我確定你想要更具體)。
創建無序列表。
循環遍歷表中的td
元素。
對於每個td
元素:
創造一個li
創建label
將td
的.contents()
移動到label
( contents
包括文本節點)。
將label
貼在li
將li
附加到ul
用ul
替換table
。
這也是一樣的,但可能更清楚:
var table = $("table"); // Limit this as appropriate
var ul = $("<ul>");
table.find("td").each(function() {
var li = $("<li>");
var label = $("<label>");
label.append($(this).contents());
li.append(label);
ul.append(li);
});
table.replaceWith(ul);
這個怎么樣?
function gerador() {
var code = $('textarea[name=message]').val();
/* prevent the creation of multiple output-blocks if someone clicks on the submit-button more than once */
if ($('#output').length < 1) {
$("body").append('<h2>Output</h2><textarea id="output" rows="10" cols="100"></textarea>');
}
/* replace all the things you want */
code = code.replace(/\<table>/g, "<ul>");
code = code.replace(/\<\/table>/g, "</ul>");
code = code.replace(/\<td>/g, "<li>");
code = code.replace(/\<\/td>/g, "</li>");
code = code.replace(/\<tr>/g, "");
code = code.replace(/\<\/tr>/g, "");
code = code.replace(/\TEXT/g, "<label>TEXT</label>");
/* output the new code */
$('#output').val(code);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.