"onclick"事件仅触发一次 [英] 'onclick' event is only triggered once
问题描述
我对javascript有问题.我不明白为什么我不能多次点击html元素.
I have a problem with javascript. I don't understand why i can't click more than once on an html element.
我将逐步进行.
以下代码是我想要做的:
The following code is what i want to do:
$(document).ready(function () {
$('.fa-star').on('click', function (e) {
e.preventDefault();
let $link = $(e.currentTarget);
$link.toggleClass('far').toggleClass('fa');
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.14.0/css/all.min.css" integrity="sha512-1PKOgIY59xJ8Co8+NE6FZ+LOAZKjy+KY8iq0G4B3CyeY6wYHN3yt9PW0XpSriVlkMXe40PTKnXrLnZ9+fkDaog==" crossorigin="anonymous" />
<a class="icons" href="#">
<i class="far fa-star" aria-hidden="true"></i>
</a>
单独使用时效果很好.
然后,我将此代码放入Symfony项目中,并使用webpack encore管理我的js文件.
Then i put this code inside my Symfony project and manage my js file with webpack encore.
以下代码已写入该文件 ajax_call.js
The code below is writen into this file ajax_call.js
#./assets/js/ajax_call.js
import $ from 'jquery';
function testHello() {
alert('Hello');
}
$(document).ready(function () {
$('.fa-star').on('click', function (e) {
e.preventDefault();
var $link = $(e.currentTarget);
$link.toggleClass('far').toggleClass('fa');
});
});
下面的代码是 webpack.config.js (您会注意到我为 ajax_call.js 添加了新的入口点)
The code below is webpack.config.js (you'll notice that i have add a new entrypoint for ajax_call.js)
var Encore = require('@symfony/webpack-encore');
// Manually configure the runtime environment if not already configured yet by the "encore" command.
// It's useful when you use tools that rely on webpack.config.js file.
if (!Encore.isRuntimeEnvironmentConfigured()) {
Encore.configureRuntimeEnvironment(process.env.NODE_ENV || 'dev');
}
Encore
// directory where compiled assets will be stored
.setOutputPath('public/build/')
// public path used by the web server to access the output path
.setPublicPath('/build')
// only needed for CDN's or sub-directory deploy
//.setManifestKeyPrefix('build/')
/*
* ENTRY CONFIG
*
* Add 1 entry for each "page" of your app
* (including one that's included on every page - e.g. "app")
*
* Each entry will result in one JavaScript file (e.g. app.js)
* and one CSS file (e.g. app.css) if your JavaScript imports CSS.
*/
.addEntry('app', './assets/js/app.js')
.addEntry('mail', './assets/js/mail.js')
.addEntry('article_list', './assets/js/mail.js')
.addEntry('ajax_call', './assets/js/ajax_call.js')
//.addEntry('page1', './assets/js/page1.js')
//.addEntry('page2', './assets/js/page2.js')
// When enabled, Webpack "splits" your files into smaller pieces for greater optimization.
.splitEntryChunks()
// will require an extra script tag for runtime.js
// but, you probably want this, unless you're building a single-page app
.enableSingleRuntimeChunk()
/*
* FEATURE CONFIG
*
* Enable & configure other features below. For a full
* list of features, see:
* https://symfony.com/doc/current/frontend.html#adding-more-features
*/
.cleanupOutputBeforeBuild()
.enableBuildNotifications()
.enableSourceMaps(!Encore.isProduction())
// enables hashed filenames (e.g. app.abc123.css)
.enableVersioning(Encore.isProduction())
// enables @babel/preset-env polyfills
.configureBabelPresetEnv((config) => {
config.useBuiltIns = 'usage';
config.corejs = 3;
})
// enables Sass/SCSS support
.enableSassLoader()
// uncomment if you use TypeScript
//.enableTypeScriptLoader()
// uncomment to get integrity="..." attributes on your script & link tags
// requires WebpackEncoreBundle 1.4 or higher
//.enableIntegrityHashes(Encore.isProduction())
// uncomment if you're having problems with a jQuery plugin
.autoProvidejQuery()
.copyFiles({
from: './assets/images',
pattern: /\.(png|jpg|jpeg|ico)$/,
// to path is relative to the build directory
to: 'images/[path][name].[hash:8].[ext]'
})
// uncomment if you use API Platform Admin (composer req api-admin)
//.enableReactPreset()
//.addEntry('admin', './assets/js/admin.js')
;
module.exports = Encore.getWebpackConfig();
然后使用我的树枝模板进行渲染:
Then my twig template for render :
{% extends '_base.html.twig' %}
{% block title %}HANFF - Menu{% endblock %}
{% block body %}
<div>
{% trans %} Bonjour, bienvenue{% endtrans %} <span id="user_login">{{ app.user.login }}</span>
</div>
<a class="icons" href="#">
<i class="far fa-star" aria-hidden="true"></i>
</a>
{% endblock %}
{% block javascripts %}
{{ parent() }}
{{ encore_entry_script_tags('ajax_call') }}
{% endblock %}
现在,我重新启动yarn,先运行Ctrl+C
,然后再运行yarn watch
.
Now i restart yarn, running Ctrl+C
and then yarn watch
.
我提供 entrypoint.js ,生成该文件是为了显示 build/目录中存在的文件:
I give entrypoint.js which is generated to show which file exist in my build/ directory :
{
"entrypoints": {
"app": {
"js": [
"/build/runtime.js",
"/build/vendors~ajax_call~app.js",
"/build/vendors~app.js",
"/build/app.js"
],
"css": [
"/build/vendors~app.css",
"/build/app.css"
]
},
"mail": {
"js": [
"/build/runtime.js",
"/build/mail.js"
],
"css": [
"/build/mail.css"
]
},
"article_list": {
"js": [
"/build/runtime.js",
"/build/article_list.js"
],
"css": [
"/build/article_list.css"
]
},
"ajax_call": {
"js": [
"/build/runtime.js",
"/build/vendors~ajax_call~app.js",
"/build/ajax_call.js"
]
}
}
}
最后,我测试了我的代码,看到我只能在星形图标上单击一次成为为onclick
事件已触发.
Finally i testing my code and see that i can click only one time on the star icon which become as the onclick
event have been triggered.
然后,如果我再次单击,则什么也没有发生.
我在on('click')
触发器的顶部放了console.log()
:
Then if i click again, nothing happens.
I have put a console.log()
on top of on('click')
trigger as :
#./assets/js/ajax_call.js
import $ from 'jquery';
$(document).ready(function () {
$('.fa-star').on('click', function (e) {
console.log('===HERE===');
e.preventDefault();
var $link = $(e.currentTarget);
$link.toggleClass('far').toggleClass('fa');
});
});
console.log()
仅出现一次(我第一次单击星形图标),然后不再显示.
The console.log()
appears just one time (first time i click on the star icon) and then no more.
我已按照此课程
我真的不明白为什么我不能做这么简单的事情! 请给我个小费,那就太好了.
I really can't understand why i can't do a thing this much simple ! Please if you could just give me a tip it would be great.
我带来了新的元素.我按以下方式编辑我的JavaScript:
I come with new element. I edit my javascript as the following :
import $ from 'jquery';
let i = 0;
$(document).ready(function () {
$('.fa-star').on('click', function (e) {
i ++;
console.log('===HERE=== ' + i);
e.preventDefault();
var $link = $(e.currentTarget);
// $link.toggleClass('far').toggleClass('fa'); <-- Comment this line
});
});
现在它可以正常工作了,'.fa-star'元素会在每次单击它时触发 onclick 事件.
And now it work, '.fa-star' element trigger the onclick event each time i click on it, as it should be.
但是现在我不明白为什么这段代码是一个问题:
But now i don't understand why this code is a problem :
$link.toggleClass('far').toggleClass('fa');
也许是问题(或解决方案)的一部分
Maybe part of the problem (or of the solution)
在创建<i></i>
元素时,它会自动解释为页面源代码中的<svg></svg>
元素.
when you create a <i></i>
element, it is automaticaly interpret as a <svg></svg>
element in the source code of the page.
这是Opera浏览器上生成的源代码:
This is the generated source code on Opera browser :
<svg class="svg-inline--fa fa-star fa-w-18" aria-hidden="true" focusable="false" data-prefix="far" data-icon="star" role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 576 512" data-fa-i2svg=""><path fill="currentColor" d="M528.1 171.5L382 150.2 316.7 17.8c-11.7-23.6-45.6-23.9-57.4 0L194 150.2 47.9 171.5c-26.2 3.8-36.7 36.1-17.7 54.6l105.7 103-25 145.5c-4.5 26.3 23.2 46 46.4 33.7L288 439.6l130.7 68.7c23.2 12.2 50.9-7.4 46.4-33.7l-25-145.5 105.7-103c19-18.5 8.5-50.8-17.7-54.6zM388.6 312.3l23.7 138.4L288 385.4l-124.3 65.3 23.7-138.4-100.6-98 139-20.2 62.2-126 62.2 126 139 20.2-100.6 98z"></path></svg>
<!-- <i class="far fa-star" aria-hidden="true"></i> -->
推荐答案
正如我在问题中所说,<i></i>
元素将被插入为<svg></svg>
元素,其中包含所有用于显示正确图标的属性.
As i have say in my question, the <i></i>
element will be interprated as a <svg></svg>
element which hold all the attribute for displaying the correct icon.
我认为这会使jQuery Selector变得困难,因为<svg><\svg>
元素不包含名称为far
或fa
的类.
I think that make thing hard for jQuery Selector, as the <svg><\svg>
element doesn't contain a class with name far
or fa
.
-
far
类变为svg-inline--far
-
fa
类成为svg-inline--fa
far
class becomesvg-inline--far
fa
class becomesvg-inline--fa
far
和fa
图标之间的区别仅由data-prefix="far"
属性进行.
And then the disctinction between far
and fa
icons is only made by the data-prefix="far"
attribute.
我想指定这种情况仅在使用fontawesome v.5
时出现,因为类名的*-o
大纲样式已被数据前缀属性替换:
I wanna specify that this kind of thing only appear when using fontawesome v.5
because the *-o
outline style of the class name have been replaced with data-prefix attributes :
https://fontawesome .com/how-to-use/on-the-web/setup/upgradeing-from-version-4
轮廓样式图标
类似地,所有具有轮廓样式(通常以-o结尾)的图标现在都具有far前缀,并且已删除了-o后缀.
Similarly, all icons that had an outlined style (and usually ended with -o) now have a prefix of far and have had their -o suffix removed.
所以我写的代码是什么,下面是什么工作(我将其移入了:
So the code i have write, and which work is the following (I have moved it into:
$(document).ready(function () {
$('.favProduct').on('click', function (e) {
e.preventDefault();
let svg = $(e.currentTarget).children('svg');
if(svg.data('prefix') === 'far') {
// Using attr, as data() doesn't update DOM element
svg.attr('data-prefix', 'fa');
}else{
svg.attr('data-prefix', 'far');
}
$(e.currentTarget).append(svg);
});
});
这篇关于"onclick"事件仅触发一次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!