添加类并删除仅在页面中的一个div上运行的类JS。无法在具有相同规格的其他产品上工作

时间:2019-05-12 11:47:25

标签: javascript wordpress

我不是JS开发人员(甚至也不是新手),我正在尝试使我在此处编写的代码能够正常工作 http://spintrak.com/newwebsiteredesign2/faqs/

我正在使用手风琴和http://prntscr.com/nnif5e,因为如果有人单击该手风琴,您会看到“蓝色”,类名中的“蓝色”将变为“红色”,这是完美的,但是,相同的功能和下面的手风琴课不起作用:/基本上我想做的是打开手风琴时,它会改变颜色,如:: visited for link,以便用户知道他们已经读过,我想如果我可以改变课(不切换),可以这样做

我使用Javascript classlist删除,然后添加onclick来更改类

function toggleColor() { document.getElementById("testwork").classList.remove("vc_toggle_color_blue");
  document.getElementById("testwork").classList.add("vc_toggle_color_red");
}

它适用于第一手风琴,而不适用于其他

1 个答案:

答案 0 :(得分:2)

乍一看,问题似乎在于您通过ID选择元素,这就是为什么它仅适用于一个元素的原因。对于这种情况,我将只使用jQuery而不是普通的javascript,因为WordPress已经加载了jQuery。您也可以使用Visual composer来分配类,因此,与其给它赋予'testwork'的ID,也不是给所有手风琴项目一个类,让我们说'accordion_color_switch'。然后代码将是:

State

那应该可以解决问题,让我知道它是否不起作用,使用可视化作曲家有时很难选择正确的元素。

编辑:切记要从您的元素中删除//Remember in WordPress we have to use the 'jQuery' selector instead of '$'. //Lets first load our function when the document has loaded. jQuery(document).ready(function(){ //We listen for the user to click on the accordion items jQuery(document).on('click', '.accordion_color_switch', function() { //We send the clicked item to the toggle color function. toggleColor(jQuery(this)); }); }); function toggleColor($target) { //If the item still has the blue color, change it, otherwise it has already been changed. if ($target.hasClass('vc_toggle_color_blue')) { $target.removeClass('vc_toggle_color_blue'); $target.addClass('vc_toggle_color_red'); } } ,因为我们不再使用它了。