[英]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.