<html>
<head>
</head>
<body>
<table>
<tr>
<td colspan="1">
<p class="Hello-7-blue1">Hello Stack Overflow1</p>
</td>
<td rowspan="1" colspan="2">
<p class="Hello-red">Hello Stack Overflow2</p>
<p class="Hello-6-tab-red">defines red color,that class want to
apply
to</p>
</td>
<td rowspan="1" colspan="1">
<p class="Hello-world-6-orange">Hello Stack Overflow3</p>
</td>
</tr>
</table>
<script>
function convertClassName(src) {
return src.replace(/^.*?-/, "");
}
$("table p").each(function() {
$(this).closest("td").addClass(convertClassName(this.className));
});
</script>
</body>
</html>
预期输出:
<td class="blue1">
<p class="Hello-7-blue1">
<td class="red">
<p class="Hello-6-tab-red">
从上面的问题来看,我想应用
中提到的类(即p class="Hello-7-blue1")应该应用到它最接近的(即td class="blue1").
而不是破折号“-”,如果我使用下划线“_”那么它的工作,但在我的页面中有破折号。所以请能帮帮我吗
最佳答案
您的正则表达式应按照以下给出的方式进行更改:
function convertClassName(src) {
return src.replace(/^.*-/, ""); //<-- Note change here
}
关于javascript - 如何引用<p class>中提到的单词将class应用于<td>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30774615/