我正在使用自定义字段动态设置DIV ID,用户将在WordPress网站的后端输入该字段。例如:“Section Title”。如何删除“Section Title”的空格并将DIV ID设置为:“SectionTitle”?
当前输出= <div id="Section Title"></div>
所需输出= <div id="SectionTitle"></div>
我已经能够替换console.log()中的空格;但不能在DIV ID本身内替换它们。
var myText = jQuery('.full_width_content').closest(".cent_full_width").attr("id");
var newMyText = myText.replace(/ /g,'');
答案 0 :(得分:2)
您可以使用str.replace(/\s/g, '');
删除空格,然后使用attr()
jQuery 设置ID。
// Remove the spaces
var str = $(".test").attr("id").replace(/\s/g, '');
// Then set the id with spaces removed
$(".test").attr("id", str);
// You can check at console
console.log($(".test").attr("id"));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="test" id="Section Title"></div>
答案 1 :(得分:2)
您必须使用此new-id
替换var myText = jQuery('.full_width_content').closest(".cent_full_width").attr("id");
var newMyText = myText.replace(/ /g,'');
// remove older id and place new id
jQuery('.full_width_content').closest(".cent_full_width").attr("id", newMyText);
(您通过代码获取的内容)
var myText = jQuery('.full_width_content').closest(".cent_full_width").attr("id");
var newMyText = myText.replace(/ /g,'');
// remove older id and place new id
jQuery('.full_width_content').closest(".cent_full_width").attr("id", newMyText);
示例示例: -
#SectionTitle{/* to show you that code is working fine */
color:green;
font-size:30px;
font-style: italic;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="cent_full_width" id="Section Title">
<div class="full_width_content">Hi</div>
</div>
{{1}}
答案 2 :(得分:1)
attr()既是setter又是getter。只需在其内部引用id属性,如下面第二行所示。
var myEl = jQuery('.full_width_content').closest(".cent_full_width");
myEl.attr("id", myEl.attr("id").replace(/\s+/g, '');