我只添加了使用CDN的JQuery,我把代码放在头部,在_head.html.erb这是一个:
<script src="https://code.jquery.com/jquery-3.7.1.min.js" integrity="sha256-/JqT3SQfawRcv/BIHPThkBvs0OEvtFFmqPF/lYI/Cxo=" crossorigin="anonymous"></script>
字符串
然后,我使用了这段代码,并将其放在show.html.erb中的某个位置
<script>
var carouselWidth = $('.carousel-inner')[0].scrollWidth;
var cardWidth = $('.carousel-item').width();
var scrollPosition = 0;
$('.carousel-control-next').on('click', function(){
console.log('next');
scrollPosition = scrollPosition + cardWidth;
$('.carousel-inner').animate({scrollLeft: scrollPosition}, 600);
});
</script>
型
我不知道还可以把jquery代码放在哪里,但是当我在浏览器中打开控制台时,我得到了这个错误:
menu-f19d6842a068966109ba6a8b3de0283869f632ec673afe222888bbeba8442401.js:7 Uncaught TypeError: Cannot read properties of null (reading 'addEventListener')
at addToggleListener (menu-f19d6842a068966109ba6a8b3de0283869f632ec673afe222888bbeba8442401.js:7:26)
at HTMLDocument.<anonymous> (menu-f19d6842a068966109ba6a8b3de0283869f632ec673afe222888bbeba8442401.js:15:9)
at S (turbo.es2017-esm.js:344:34)
at Object.notifyApplicationAfterPageLoad (turbo.es2017-esm.js:3158:16)
at Object.pageBecameInteractive (turbo.es2017-esm.js:3080:14)
at he.pageIsInteractive (turbo.es2017-esm.js:2486:27)
at he.pageIsComplete (turbo.es2017-esm.js:2490:14)
at HTMLDocument.interpretReadyState (turbo.es2017-esm.js:2458:22)
addToggleListener @ menu-f19d6842a068966109ba6a8b3de0283869f632ec673afe222888bbeba8442401.js:7
(anonymous) @ menu-f19d6842a068966109ba6a8b3de0283869f632ec673afe222888bbeba8442401.js:15
S @ turbo.es2017-esm.js:344
notifyApplicationAfterPageLoad @ turbo.es2017-esm.js:3158
pageBecameInteractive @ turbo.es2017-esm.js:3080
pageIsInteractive @ turbo.es2017-esm.js:2486
pageIsComplete @ turbo.es2017-esm.js:2490
interpretReadyState @ turbo.es2017-esm.js:2458
型
编辑
menu.js文件:
function addToggleListener(selected_id, menu_id, toggle_class) {
let selected_element = document.querySelector(`#${selected_id}`);
selected_element.addEventListener('click', function(event){
event.preventDefault();
let menu = document.querySelector(`#${menu_id}`)
menu.classList.toggle(toggle_class);
});
}
document.addEventListener('turbo:load', function(){
addToggleListener('hamburger', 'navbar-menu', 'collapse');
addToggleListener('account', 'dropdown-menu', 'active');
});
型
1条答案
按热度按时间gcuhipw91#
你想给
selected_element.addEventListener
元素添加一个监听器,但页面上没有“hamburger”或“account”元素。使用事件委托是Turbo更好的方法:字符串
您可能需要考虑使用
data
属性来控制模板的行为。这样您就不必添加更多的toggleMenu
调用:x
的字符串