我这里有一个非常奇怪的错误。 checkHand()函数在页面加载时运行,但是当我使用onchange属性触发同一函数时,它将引发未定义的错误。
我正在使用webpack编译以下代码,但是当我不使用webpack并制作一个仅用于.js文件的文件时,它可以完美地工作。
页面加载后,如果我转到浏览器控制台并键入checkHand(),它将显示为函数未定义。我发现它已经在页面加载时触发了,这很奇怪。
以下代码:
'use strict';
var hand = [];
var valuesArr = [];
var suitsArr = [];
function checkHand() {
var resultString;
for(var i = 0; i < 5; i++) {
hand[i] = document.getElementById(`card_${i}`).value
}
console.log(hand);
}
// Declare all card values
var cardValues = ['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K'];
// Declare all suit values
var suitValues = ['♠', '♣', '♥', '♦'];
var table = '';
// loop over 5 cards
for(var cardNum = 0; cardNum < 5; cardNum ++){
// append 5 select elements to the DOM table.
table += `<select id="card_${cardNum}" onchange="checkHand()">`;
for(var i = 0; i < 52; i++) {
table += `<option value="${i}">${cardValues[i % 13]} ${suitValues[Math.floor(i / 13)]}</option>`;
}
table += '</select>';
}
document.getElementById("table").innerHTML = table;
checkHand();
我在做什么错。
下面是我的webpack配置
const path = require('path');
const webpack = require('webpack');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
module.exports = {
context: path.resolve(__dirname, './src'),
watch: true,
entry: {
bundle: ['./scripts/main.js', './scss/main.scss'],
},
devServer: {
contentBase: './dist',
},
output: {
path: path.resolve(__dirname, './dist'),
publicPath: '/dist/',
filename: '[name].js'
},
module: {
rules: [
{
test: /\.(css|scss)$/,
use: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: [
{
loader: 'css-loader',
options: {
minimize: true || {/* CSSNano Options */}
}
},
{
loader: 'postcss-loader'
},
{
loader: 'sass-loader'
}
]
})
}]
},
plugins: [
new ExtractTextPlugin('[name].css'),
new CopyWebpackPlugin([
{from: '../src/images', to: 'images'},
{from: './*.html'}
]),
new CleanWebpackPlugin(['dist']),
]
}