我使用带有 slider 的 React.js 创建了一个网站,该 slider 使用 jQuery 进行自动滚动。我已经在沙箱 (Codepen.io) 中完成了,效果很好。在我开始使用“create-react-app”和 WebStorm 之后。我做了什么: 在我写的命令行中:
"npm install create-react-app"
"npm install jquery"
"create-react-app my-app"
之后,我用 WebStorm 2018.2 (x86) 打开了“我的应用程序”,并将我所有的代码从沙箱中转移到其中,添加了一些“导入”命令。所以 slider 现在不起作用(它就像缺少 JavaScript 代码一样工作)。 我删除了额外的代码。这就是剩下的: JS代码
import React from 'react';
import $ from 'jquery'
/*jshint esversion: 6 */
class App extends React.Component {
render() {
return <div><div className = "slider"><input type = "radio" name = "slides" id = "slide1" /><input type = "radio" name = "slides" id = "slide2" /><input type = "radio" name = "slides" id = "slide3" /><input type = "radio" name = "slides" id = "slide4" /><input type = "radio" name = "slides" id = "slide5" />
<input type = "radio" name = "slides" id = "slide6" /><div className = "captions"><div className = "c2" > Prediction 2 </div><div className = "c3"> Prediction 3 </div> <div className = "c4" > Prediction 4 </div> <div className = "c5" > Prediction 5 </div>
<div className = "c6" > Prediction 6 < /div></div></div> <div className = "controls" ><label htmlFor = "slide1" /><label htmlFor = "slide2" /><label htmlFor = "slide3" /><label htmlFor = "slide4" /><label htmlFor = "slide5" /><label htmlFor = "slide6" /></div></div>;
}
}
ReactDOM.render( <App/> , document.getElementById('root'));
//script for slider's autoscrolling
let inputs = $('input[type=radio]');
console.log(inputs);
let next;
let intervals = setInterval(() => {
next = inputs.filter(":checked").next('input');
if (!next.length) next = inputs.first();
next.prop('checked', true);
}, 2000);
inputs.change(() => {
clearInterval(intervals);
intervals = setInterval(function() {
next = inputs.filter(":checked").next('input');
if (next.length) next.prop('checked', true);
else inputs.first().prop('checked', true);
}, 2000);
});
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://code.jquery.com/jquery-3.3.1.js" integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60=" crossorigin="anonymous"></script>
<meta charset="utf-8">
<title>React App</title>
</head>
<body>
<div id="root"></div>
</body>
</html>
在控制台中我看到:jQuery.fn.init(0)
。我应该如何捕捉输入?
最佳答案
谢谢@connexo 的回答:
$(document).ready(()=>{
let inputs = $('input[type=radio]');
console.log(inputs);
let next;
let intervals = setInterval(() => {
next = inputs.filter(":checked").next('input');
if (!next.length) next = inputs.first();
next.prop('checked', true);
}, 2000);
inputs.change(() => {
clearInterval(intervals);
intervals = setInterval(function() {
next = inputs.filter(":checked").next('input');
if (next.length) next.prop('checked', true);
else inputs.first().prop('checked', true);
}, 2000);
});
})
现在可以了!清楚一点,如果没有这个声明,我试图在输入标签未加载时访问它们。
关于javascript - WebStorm:无法使用 jQuery 捕获 <input/>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53333397/