gpt4 book ai didi

javascript - 使用 jQuery 修改类

转载 作者:行者123 更新时间:2023-12-02 19:29:43 24 4
gpt4 key购买 nike

<span class="here one-two-del-del other1">test</span>
<span class="here one-two-aaa o2ther">test</span>
<span class="here one-two-dsf other3">test</span>
<span class="here one-two-213 o4ther">test</span>
<span class="here one-two-sdf other5">test</span>
<span class="here one-two-sdff o6ther">test</span>

<span class="set one-two-aaaa">set 1</span> <br />
<span class="set one-two-bb-fff">set 2</span> <br />
<span class="set one-two-vcvc">set 3</span> <br />
<span class="set one-two-fgdfg-dfgfd-fgf">set 4</span> <br />​

​$('.set').click(function(){
$('#here').???
})​

我想 - 如果我点击 .set 那么这应该得到自己的类并替换为所有 .here。

例如,如果我点击set 2,那么所有带有 class .here 的跨度应该是:

​<span class="here one-two-bb-fff other1">test</span>
<span class="here one-two-bb-fff o2ther">test</span>
<span class="here one-two-bb-fff other3">test</span>
<span class="here one-two-bb-fff o4ther">test</span>
<span class="here one-two-bb-fff other5">test</span>
<span class="here one-two-bb-fff o6ther">test</span>

我不能使用removeClass,因为我不知道当前的类如何。如果我使用 .attr('class', 'new') 那么这会替换所有类,但我仍然必须有类 other1、o2ther 等

http://jsfiddle.net/NNhDd/

也许我必须使用正则表达式?

最佳答案

HTML

<span class="here one-two-del-del other1">test</span>
<span class="here one-two-aaa o2ther">test</span>
<span class="here one-two-dsf other3">test</span>
<span class="here one-two-213 o4ther">test</span>
<span class="here one-two-sdf other5">test</span>
<span class="here one-two-sdff o6ther">test</span>

<br />

<span class="set one-two-aaaa">set 1</span> <br />
<span class="set one-two-bb-fff">set 2</span> <br />
<span class="set one-two-vcvc">set 3</span> <br />
<span class="set one-two-fgdfg-dfgfd-fgf">set 4</span>

JavaScript

$('.set').click(function () {
var replaceWith = $(this).attr('class');
// Remove the "set " from replaceWith
replaceWith = replaceWith.replace(/set ?/g, '');

$('.here').each(function () {
var newClass = $(this).attr('class');
newClass = newClass.replace(/one-two-[^ $]+/, '');
newClass = newClass + ' ' + replaceWith;
// Now set the new class
$(this).attr('class', newClass);
});
})

这是一个 fiddle :http://jsfiddle.net/NNhDd/3/

关于javascript - 使用 jQuery 修改类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11645354/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com