如何将html表(我将在下面提供代码)转换为<div>元素?长话短说,我使用的是一个php脚本,它将内容输出到html表中,事实证明编辑php并将表元素转换为<div>非常困难。下面是html表代码:

<table><tbody><tr data-marker="0"><td class="mapp-marker"><img class="mapp-icon" src="http://www.walmartchicago.com/wp-content/plugins/mappress-google-maps-for-wordpress/icons/walmart-yellow.png"></td><td><b>Walmart Neighborhood Market<br></b><a href="#" class="poi_list_directions">Get Directions</a></td></tr><tr data-marker="1"><td class="mapp-marker"><img class="mapp-icon" src="http://www.walmartchicago.com/wp-content/plugins/mappress-google-maps-for-wordpress/icons/walmart-red.png"></td><td><b>Walmart Express<br></b><a href="#" class="poi_list_directions">Get Directions</a></td></tr><tr data-marker="2"><td class="mapp-marker"><img class="mapp-icon" src="http://www.walmartchicago.com/wp-content/plugins/mappress-google-maps-for-wordpress/icons/walmart-red.png"></td><td><b>Walmart Express<br></b><a href="#" class="poi_list_directions">Get Directions</a></td></tr><tr data-marker="3"><td class="mapp-marker"><img class="mapp-icon" src="http://www.walmartchicago.com/wp-content/plugins/mappress-google-maps-for-wordpress/icons/walmart-blue.png"></td><td><b>Walmart Supercenter<br></b><a href="#" class="poi_list_directions">Get Directions</a></td></tr><tr data-marker="4"><td class="mapp-marker"><img class="mapp-icon" src="http://www.walmartchicago.com/wp-content/plugins/mappress-google-maps-for-wordpress/icons/walmart-blue.png"></td><td><b>Walmart Supercenter<br></b><a href="#" class="poi_list_directions">Get Directions</a></td></tr></tbody></table>

最佳答案

无需循环遍历元素和复制属性,只需将表内容作为字符串拉取并运行一个简单的字符串替换…

$('table').replaceWith( $('table').html()
   .replace(/<tbody/gi, "<div id='table'")
   .replace(/<tr/gi, "<div")
   .replace(/<\/tr>/gi, "</div>")
   .replace(/<td/gi, "<span")
   .replace(/<\/td>/gi, "</span>")
   .replace(/<\/tbody/gi, "<\/div")
);

…或者,如果你想要一个无序的列表…
$('table').replaceWith( $('table').html()
   .replace(/<tbody/gi, "<ul id='table'")
   .replace(/<tr/gi, "<li")
   .replace(/<\/tr>/gi, "</li>")
   .replace(/<td/gi, "<span")
   .replace(/<\/td>/gi, "</span>")
   .replace(/<\/tbody/gi, "<\/ul")
);

这也将保留您的类和属性。
也许最好的解决方案与jquery无关,但是php……您可以在从php输出之前使用php的str_replace()执行相同的操作吗?
$table_str = //table string here
$UL_str = str_replace('<tbody', '<ul id="table"', $table_str);
$UL_str = str_replace('<tr', '<li', $UL_str);
$UL_str = str_replace('</tr', '</li', $UL_str);
$UL_str = str_replace('<td', '<span', $UL_str);
$UL_str = str_replace('</td', '</span', $UL_str);
$UL_str = str_replace('</tbody', '</ul"', $UL_str);

关于jquery - 如何使用jQuery将HTML表转换为<div>?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9229856/

10-09 15:52