jquery에서 함수를 실행하는 방법
저는 프로그래밍 초보자이고 JQuery에 함수를 저장하고 여러 위치에서 실행하는 방법을 알 수 없습니다.
나는 가지고있다:
$(function () {
$("div.class").click(function(){
//Doo something
});
$("div.secondclass").click(function(){
//Doo something
});
});
이제 2 개의 "// Doo somethings"는 동일하며 동일한 코드를 다시 작성하고 싶지 않습니다.
내가 넣으면 :
$(function () {
function doosomething ()
{
//Doo something
}
$("div.class").click(doosomething);
$("div.secondclass").click(doosomething);
});
클릭 할 때만 아니라 페이지로드시 함수를 실행합니다.
이 작업을 올바르게 수행하는 방법은 무엇입니까?
감사!
다음은 잘 작동합니다.
$(function() {
// Way 1
function doosomething()
{
//Doo something
}
// Way 2, equivalent to Way 1
var doosomething = function() {
// Doo something
}
$("div.class").click(doosomething);
$("div.secondclass").click(doosomething);
});
기본적으로 사용하는 것과 동일한 범위에서 함수를 선언합니다 (JavaScript는 Closure 를 사용 하여 범위를 결정합니다).
이제 JavaScript의 함수는 다른 객체처럼 동작 doosomething
하므로 다음을 사용하여 클릭시 호출 할 함수로 간단히 할당 할 수 있습니다..click(doosomething);
Your function will not execute until you call it using doosomething()
(doosomething
without the ()
refers to the function but doesn't call it) or another function calls in (in this case, the click
handler).
I would do it this way:
(function($) {
jQuery.fn.doSomething = function() {
return this.each(function() {
var $this = $(this);
$this.click(function(event) {
event.preventDefault();
// Your function goes here
});
});
};
})(jQuery);
Then on document ready you can do stuff like this:
$(document).ready(function() {
$('#div1').doSomething();
$('#div2').doSomething();
});
function doosomething ()
{
//Doo something
}
$(function () {
$("div.class").click(doosomething);
$("div.secondclass").click(doosomething);
});
Alternatively (I'd say preferably), you can do it like this:
$(function () {
$("div.class, div.secondclass").click(function(){
//Doo something
});
});
You can also do this - Since you want one function to be used everywhere, you can do so by directly calling JqueryObject.function(). For example if you want to create your own function to manipulate any CSS on an element:
jQuery.fn.doSomething = function () {
this.css("position","absolute");
return this;
}
And the way to call it:
$("#someRandomDiv").doSomething();
Is this the most obfuscated solution possible? I don't believe the idea of jQuery was to create code like this.There's also the presumption that we don't want to bubble events, which is probably wrong.
Simple moving doosomething()
outside of $(function(){}
will cause it to have global scope and keep the code simple/readable.
참고URL : https://stackoverflow.com/questions/1191833/how-to-run-a-function-in-jquery
'IT TIP' 카테고리의 다른 글
Bootstrap 3 Carousel이 새 슬라이드로 슬라이드하는 대신 새 슬라이드로 페이드 됨 (0) | 2020.11.22 |
---|---|
iOS 프로젝트에서 Pods-resources.sh 권한이 거부되었습니다. (0) | 2020.11.22 |
C #에서 한 번에 여러 루프를 중단하는 방법은 무엇입니까? (0) | 2020.11.22 |
쉘 스크립트를 전역으로 만드는 방법은 무엇입니까? (0) | 2020.11.22 |
블루투스가 프로그래밍 방식으로 활성화되었는지 확인하는 방법은 무엇입니까? (0) | 2020.11.22 |