我可以使用 if 语句来更改 Swiper javascript 滑块的 API 选项吗?

Can I use an if statement to change the API options of the Swiper javascript slider?

抱歉,如果这是一个愚蠢的问题。我正在使用由 iDangerous 开发的 Swiper javascript 滑块。它带有我的 HTML 文件中的初始化字段,其中包含滑块的初始化选项。

我现在需要在网页中搜索名为 #editor-content 的特定元素。如果找到元素,我需要将 Swiper 初始化的 simulateTouch 选项设置为 false. 如果没有找到元素,则 stimulateTouch 选项应设置为 true.

我正在使用 jQuery 来完成查找元素。我正在使用 if(($('#editor-content').length)){...} 来完成此操作。这部分工作得很好。

这是 Swiper 初始化的样子...

<script>
swiper = new Swiper('.swiper-container', {
spaceBetween: 30,
centeredSlides: true,

// This is the option that needs to be set to true/false depending on whether the #editor-content element exists in the webpage or not...
stimulateTouch = false;***

autoplay: {
delay: 2500,
disableOnInteraction: true,
},
pagination: {
el: '.swiper-pagination',
clickable: true,
},
navigation: {
nextEl: '.swiper-button-next',
prevEl: '.swiper-button-prev',
},
});
</script>

到目前为止,我已尝试根据结果以不同方式初始化滑块。如果找到该元素,则使用禁用的选项初始化滑动器。如果没有,请使用启用的选项初始化刷卡器。那行不通(请参阅下面的代码——我对缩进混乱感到非常抱歉):

<script>
var swiper = undefined;
function initSwiper() {

// If the jQuery detects an #editor-content element (meaning you're in the editor...)
if((jQuery('#editor-content').length)){

swiper = new Swiper('.swiper-container', {
spaceBetween: 30,
centeredSlides: true,

// Element found, so initialize the slider with option below set to false
simulateTouch = false,

autoplay: {
delay: 2500,
disableOnInteraction: true,
},
pagination: {
el: '.swiper-pagination',
clickable: true,
},
navigation: {
nextEl: '.swiper-button-next',
prevEl: '.swiper-button-prev',
},
});

} else {

var swiper2 = new Swiper('.swiper-container', {
spaceBetween: 30,
centeredSlides: true,

// Element not found, so initialize the slider with option below set to true
simulateTouch = true,

autoplay: {
delay: 2500,
disableOnInteraction: true,
},
pagination: {
el: '.swiper-pagination',
clickable: true,
},
navigation: {
nextEl: '.swiper-button-next',
prevEl: '.swiper-button-prev',
},
});

}

}
// Initialize the function      
initSwiper();
</script>

我希望滑块在 #editor-content 确实存在时将 stimulateTouch 选项设置为 false,并在 body 中的元素不存在时将选项设置为 true。但到目前为止,我尝试的代码只是让整个滑块 js 无法运行。帮助?

如果您 运行 您的代码通过 Javascript 验证器(例如:http://esprima.org/demo/validate.html),您会发现第 12 行存在语法错误。

stimulateTouch = false,

需要

stimulateTouch: false,

根据其他属性。

仅供参考,您可能需要研究使用 Chrome 开发人员工具或其他一些调试工具来解决此类小问题。如果您有任何语法错误,控制台会通知您,您可以使用调试器设置断点并逐行单步执行代码,这样您就可以找到事情开始出现问题的确切位置。