jQuery 中的字符串操作
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/602438/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
String manipulation in jQuery
提问by juan
I have a div which collapses clicking on a text header. I want to change the header from "+ filters" to "- filters" accordingly (when the div is collapsed or expanded)
我有一个 div 折叠点击文本标题。我想相应地将标题从“+过滤器”更改为“-过滤器”(当div折叠或展开时)
How can I perform this with jQuery?
如何使用 jQuery 执行此操作?
if (headerDiv.text() starts with "+")
replace "+" with "-"
else
replace "-" with "+"
回答by juan
Never mind, I figured it out
没关系,我想通了
if ($(header).text().trim().charAt(0) == "+")
$(header).text($(header).text().replace("+", "-"));
else
$(header).text($(header).text().replace("-", "+"));
If this is not the correct way, I'd appreciate a heads up
如果这不是正确的方法,我将不胜感激
回答by fmsf
I would do:
我会做:
var plus_string = "<span class=/"plus/">+</span>";
var minus_string = "<span class=/"minus/">-</span>";
if($("div.header").hasClass("plus")){
$("div.header").removeClass("plus");
$("div.header").addClass("minus");
$("div.header").append(plus_string);
$("span.plus").remove();
} else (... the reverse of the above...)
This because i would use the class plus and minus to handle a bit of css to change the appearance of the header div. As you're probably already doing that, you can play a bit with it like this :)
这是因为我会使用类加号和减号来处理一些 css 来改变标题 div 的外观。因为您可能已经这样做了,所以您可以像这样玩一下:)
回答by Andrew Clark
keep it simple, why do you need to parse it out? your just replacing one string with another.
保持简单,你为什么需要解析它?你只是用另一个替换一个字符串。
if(headerDiv.text() == '+ filters')
{
headerDiv.text() == '- filters';
}
elseif(headerDiv.text() == '- filters')
{
headerDiv.text() == '+ filters';
}