event.preventDefault()를 사용한 후 이벤트를 트리거하는 방법
나는 그것을 발사할 준비가 될 때까지 이벤트를 개최하고 싶습니다.
$('.button').live('click', function(e){
e.preventDefault();
// do lots of stuff
e.run() //this proceeds with the normal event
}
다음과 동등한 것이 있습니까?run()
위에 설명된 기능은 무엇입니까?
아니요. 일단 행사가 취소되면 취소됩니다.
그러나 나중에 플래그를 사용하여 사용자 지정 코드가 이미 실행되었는지 여부를 확인하여 이벤트를 다시 시작할 수 있습니다(예: 노골적인 네임스페이스 오염은 무시하십시오).
var lots_of_stuff_already_done = false;
$('.button').on('click', function(e) {
if (lots_of_stuff_already_done) {
lots_of_stuff_already_done = false; // reset flag
return; // let the event bubble away
}
e.preventDefault();
// do lots of stuff
lots_of_stuff_already_done = true; // set flag
$(this).trigger('click');
});
더 일반화된 변형(글로벌 네임스페이스 오염 방지라는 추가 이점 포함)은 다음과 같습니다.
function onWithPrecondition(callback) {
var isDone = false;
return function(e) {
if (isDone === true)
{
isDone = false;
return;
}
e.preventDefault();
callback.apply(this, arguments);
isDone = true;
$(this).trigger(e.type);
}
}
용도:
var someThingsThatNeedToBeDoneFirst = function() { /* ... */ } // do whatever you need
$('.button').on('click', onWithPrecondition(someThingsThatNeedToBeDoneFirst));
보너스 초미니멀리즘 jQuery 플러그인:Promise
지원:
(function( $ ) {
$.fn.onButFirst = function(eventName, /* the name of the event to bind to, e.g. 'click' */
workToBeDoneFirst, /* callback that must complete before the event is re-fired */
workDoneCallback /* optional callback to execute before the event is left to bubble away */) {
var isDone = false;
this.on(eventName, function(e) {
if (isDone === true) {
isDone = false;
workDoneCallback && workDoneCallback.apply(this, arguments);
return;
}
e.preventDefault();
// capture target to re-fire event at
var $target = $(this);
// set up callback for when workToBeDoneFirst has completed
var successfullyCompleted = function() {
isDone = true;
$target.trigger(e.type);
};
// execute workToBeDoneFirst callback
var workResult = workToBeDoneFirst.apply(this, arguments);
// check if workToBeDoneFirst returned a promise
if (workResult && $.isFunction(workResult.then))
{
workResult.then(successfullyCompleted);
}
else
{
successfullyCompleted();
}
});
return this;
};
}(jQuery));
용도:
$('.button').onButFirst('click',
function(){
console.log('doing lots of work!');
},
function(){
console.log('done lots of work!');
});
승인된 답변의 최신 버전입니다.
간단한 버전:
$('#form').on('submit', function(e, options) {
options = options || {};
if ( !options.lots_of_stuff_done ) {
e.preventDefault();
$.ajax({
/* do lots of stuff */
}).then(function() {
// retrigger the submit event with lots_of_stuff_done set to true
$(e.currentTarget).trigger('submit', { 'lots_of_stuff_done': true });
});
} else {
/* allow default behavior to happen */
}
});
이와 같은 경우에는 기존 양식 코드가 작동하지만 양식을 제출하기 전에 전자 메일 주소 확인과 같은 기능을 추가하여 양식을 향상시킬 수 있습니다.백엔드 폼 포스트 코드를 파고드는 대신 API를 작성한 다음 프론트 엔드 코드를 업데이트하여 폼이 기존 POST를 수행하도록 허용할 수 있습니다.
이를 위해 제가 여기에 쓴 것과 유사한 코드를 구현할 수 있습니다.
$('#signup_form').on('submit', function(e, options) {
options = options || {};
if ( !options.email_check_complete ) {
e.preventDefault(); // Prevent form from submitting.
$.ajax({
url: '/api/check_email'
type: 'get',
contentType: 'application/json',
data: {
'email_address': $('email').val()
}
})
.then(function() {
// e.type === 'submit', if you want this to be more dynamic
$(e.currentTarget).trigger(e.type, { 'email_check_complete': true });
})
.fail(function() {
alert('Email address is not valid. Please fix and try again.');
})
} else {
/**
Do traditional <form> post.
This code will be hit on the second pass through this handler because
the 'email_check_complete' option was passed in with the event.
*/
$('#notifications').html('Saving your personal settings...').fadeIn();
}
});
당신은 다음과 같은 것을 할 수 있습니다.
$(this).unbind('click').click();
속성 재정의isDefaultPrevented
다음과 같이:
$('a').click(function(evt){
evt.preventDefault();
// in async handler (ajax/timer) do these actions:
setTimeout(function(){
// override prevented flag to prevent jquery from discarding event
evt.isDefaultPrevented = function(){ return false; }
// retrigger with the exactly same event data
$(this).trigger(evt);
}, 1000);
}
IMHO, 이것은 정확히 동일한 데이터로 이벤트를 재트리거하는 가장 완벽한 방법입니다.
보다 최근의 답변은 능숙하게 사용합니다.jQuery.one()
$('form').one('submit', function(e) {
e.preventDefault();
// do your things ...
// and when you done:
$(this).submit();
});
https://stackoverflow.com/a/41440902/510905
사용할 수 있습니다.currentTarget
의event
예제는 양식 제출을 진행하는 방법을 보여줍니다.마찬가지로 당신은 기능을 얻을 수 있습니다.onclick
속성 등
$('form').on('submit', function(event) {
event.preventDefault();
// code
event.currentTarget.submit();
});
수행하지 마십시오.e.preventDefault();
또는 조건부로 수행합니다.
원래 이벤트 작업이 발생할 때는 확실히 변경할 수 없습니다.
나중에 원래 UI 이벤트를 "재작성"하려면(예: AJAX 요청 콜백) 다른 방법으로 위장해야 합니다(예: vzwick의 답변).그런 접근법의 유용성에 의문을 제기하지만요
제가 사용하는 접근 방식은 다음과 같습니다.
$('a').on('click', function(event){
if (yourCondition === true) { //Put here the condition you want
event.preventDefault(); // Here triggering stops
// Here you can put code relevant when event stops;
return;
}
// Here your event works as expected and continue triggering
// Here you can put code you want before triggering
});
"물건의 집합"이 비동기식으로 무언가를 하지 않는 한 이것은 절대적으로 불필요합니다 - 이벤트는 그의 길을 가는 모든 핸들러를 순차적으로 호출할 것입니다, 그래서 부모-클릭 이벤트가 있는 경우 이것은 아이의 온클릭 이벤트가 완전히 처리된 후에 실행될 것입니다. 자바스크립트는 여기서 "멀티스레딩"을 하지 않습니다.topping" 이벤트 처리가 필요합니다. 결론: 동일한 핸들러에서 이벤트를 다시 시작하기 위해 "일시 중지"하는 것은 의미가 없습니다.
만약 "물건의 이동"이 비동기적인 것이라면, 이것은 또한 그들이 해야 할 일을 하는 비동기적인 것들(비동기적인 것들)을 막고 모든 것이 순서대로 진행되도록 하기 때문에 말이 되지 않습니다(우리가 첫 번째 단락으로 돌아오는 곳).
또 다른 해결책은 이벤트 수신기에서 window.setTimeout을 사용하여 이벤트 프로세스가 완료된 후 코드를 실행하는 것입니다.뭐랄까...
window.setTimeout(function() {
// do your thing
}, 0);
나는 기다리는 것을 신경 쓰지 않기 때문에 그 기간 동안 0을 사용합니다.
앵커 태그로 작업하는 경우 승인된 솔루션이 작동하지 않습니다.이 경우 통화 후 링크를 다시 클릭할 수 없습니다.e.preventDefault()
jQuery에서 생성된 클릭 이벤트는 네이티브 브라우저 이벤트 위의 레이어에 불과하기 때문입니다.따라서 앵커 태그에서 '클릭' 이벤트를 트리거하면 링크가 따라가지 않습니다.대신 기본 브라우저 이벤트를 시작할 수 있는 jquery-simulate와 같은 라이브러리를 사용할 수 있습니다.
이에 대한 자세한 내용은 이 링크에서 확인할 수 있습니다.
타이머와 함께 사용하거나 타이머 없이 사용할 수 있습니다.
const form = document.querySelector('#form');
form.addEventListener('submit', (x) => {
x.preventDefault()
// Ajax or nay Code
setTimeout(() => {
x.target.submit();
}, 1000)
})
저는 이 주제가 오래된 것을 알지만 제가 기여할 수 있다고 생각합니다.이미 알고 있는 경우 핸들러 기능에서 특정 요소에 대한 이벤트의 기본 동작을 언제든지 트리거할 수 있습니다.예를 들어, 재설정 버튼에서 클릭 이벤트를 트리거하면 실제로 가장 가까운 형식의 재설정 기능을 기본 동작으로 호출합니다.핸들러 기능에서 기본값 방지 기능을 사용한 후 핸들러 코드에서 가장 가까운 형식으로 재설정 기능을 호출하여 기본 동작을 호출할 수 있습니다.
이 예제가 도움이 될 수 있으면 일부 링크에 "custom confirm popin"을 추가합니다(나는 "$ui" 코드를 유지합니다).Modal.confirm"은 원래 작업을 실행하는 콜백에 대한 예제입니다.):
//Register "custom confirm popin" on click on specific links
$(document).on(
"click",
"A.confirm",
function(event){
//prevent default click action
event.preventDefault();
//show "custom confirm popin"
$.ui.Modal.confirm(
//popin text
"Do you confirm ?",
//action on click 'ok'
function() {
//Unregister handler (prevent loop)
$(document).off("click", "A.confirm");
//Do default click action
$(event.target)[0].click();
}
);
}
);
만약 당신이 양식에 이벤트 청취자를 추가하고 제출을 기다리는 경우, 당신이 확인해야 할 것을 확인한 후에 .submitie로 양식의 제출을 호출할 수 있습니다.
const checkoutForm = document.getElementById('checkout-form');
const cart = {};
if (checkoutForm) {
checkoutForm.addEventListener('submit', e => {
e.preventDefault();
if(JSON.stringify(cart) === '{}'){
console.log('YOUR CART IS EMPTY')
alert('YOUR CART IS EMPTY');
return;
}
else{
checkoutForm.submit();
}
})
}
<form id="checkout-form" action="action-page" method="post">
<input type="text" name="name" />
<button>Submit</button>
</form>
이를 통해 암호의 강도를 확인하고 필요한 모든 필드에 올바른 데이터가 있는지 확인하는 것과 같은 양식 제출 문제를 해결할 수 있습니다.
여기에 기본값을 방지하고 내부에서 "클릭"을 트리거하는 제 오래된 아이디어가 있습니다.저는 단지 "예방" 인수를 함수에 전달할 뿐입니다.
$(document).on('click', '.attachments_all', function(e, prevent = true){
if(prevent){
e.preventDefault();
var button = $(this);
var id = button.data('id');
$.ajax({
type: 'POST',
url: window.location.protocol + '//' + window.location.host + path + '/attachments/attachments-in-order/' + id,
dataType: 'json',
success: function(data){
if(data.success && data.attachments){
button.trigger('click', false);
} else {
swal({
title: "Brak załączników!",
text: "To zamówienie nie posiada żadnych załączników!",
type: "error"
});
return;
}
}
});
}
});
누군가 유용한 정보를 얻기를 바랍니다.
마우스 입력으로 할 수 있는 간단한 것이라면.
$(document).on('mouseenter','.button',function(e) {
//if class not exist yet -> do ajax
//after complete add class
$(this).addClass('ajx-event-completed');
});
$(document).on('click','.button',function(e) {
if($(this).hasClass('ajx-event-completed')){
//do something else
}
else{
e.preventDefault();
//we are CLOSED today! See you next week
}
//do more
});
언급URL : https://stackoverflow.com/questions/7610871/how-to-trigger-an-event-after-using-event-preventdefault
'sourcetip' 카테고리의 다른 글
송장, 송장 라인 및 수정사항에 대한 데이터베이스 설계 (0) | 2023.08.21 |
---|---|
SQL 서버 실제 데이터 유형, C#에 해당하는 것은 무엇입니까? (0) | 2023.08.21 |
IMG dir는 db에 저장할 수 없지만 쿼리에 사용된 동일한 변수에서 볼 수 있습니다. (0) | 2023.08.21 |
Spring Security를 사용한 HTTPS 로그인이 HTTP로 리디렉션 (0) | 2023.08.16 |
유형 및 이름별 대상 입력(계속) (0) | 2023.08.16 |