Вызов определенной пользователем функции в jQuery - PullRequest
56 голосов
/ 26 марта 2010

Я пытаюсь вызвать пользовательскую функцию в jQuery:

$(document).ready(function() {
  $('#btnSun').click(function() {
    myFunction();
  });
  $.fn.myFunction = function() {
    alert('hi');
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="btnSun">Say hello!</button>

Я также попробовал следующее:

$(document).ready(function() {
  $('#btnSun').click(function() {
    myFunction();
  });
});

function myFunction() {
  alert('hi');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="btnSun">Say hello!</button>

Кажется, это не работает! Есть идеи, где я не прав?

Ответы [ 10 ]

72 голосов
/ 26 марта 2010

Если вы хотите вызвать обычную функцию через событие jQuery, вы можете сделать это следующим образом:

$(document).ready(function() {
  $('#btnSun').click(myFunction);
});

function myFunction() {
  alert('hi');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="btnSun">Say hello!</button>
32 голосов
/ 07 декабря 2010

Просто попробуйте это. Это всегда работает.

$(document).ready(function() {
  $('#btnSun').click(function() {
    $.fn.myFunction();
  });
  $.fn.myFunction = function() {
    alert('hi');
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="btnSun">Say hello!</button>
12 голосов
/ 26 марта 2010

Они называются плагинами , как прокомментировал Jaboc. Чтобы иметь смысл, функция плагина должна что-то делать с элементом, через который она вызывается. Учтите следующее:

jQuery.fn.make_me_red = function() {
    return this.each(function() {
        this.style.color = 'red';
    });
};

$('a').make_me_red();
9 голосов
/ 11 января 2012

Следующий метод правильный

$(document).ready(function() {
    $('#btnSun').click(function(){
        $(this).myFunction();
     });
     $.fn.myFunction = function() { 
        alert('hi'); 
     }
});
7 голосов
/ 26 марта 2010

Попробуйте это $('div').myFunction();

Это должно работать

$(document).ready(function() {
 $('#btnSun').click(function(){
  myFunction();
 });

function myFunction()
{
alert('hi');
}
3 голосов
/ 29 марта 2010
jQuery.fn.make_me_red = function() {
    return this.each(function() {
        this.style.color = 'red';
    });
};

$('a').make_me_red() // - instead of this you can use $(this).make_me_red() instead for better readability.
1 голос
/ 15 июля 2013
$(document).ready(function() {
  $('#btnSun').click(function(){

      myFunction();

   });

   $.fn.myFunction = function() { 
     alert('hi'); 

    }; 
});

Пут ';'после определения функции ...

0 голосов
/ 18 марта 2019
jQuery.fn.clear = function()
{
    var $form = $(this);

    $form.find('input:text, input:password, input:file, textarea').val('');
    $form.find('select option:selected').removeAttr('selected');
    $form.find('input:checkbox, input:radio').removeAttr('checked');

    return this;
}; 


$('#my-form').clear();
0 голосов
/ 08 апреля 2018

function hello(){
    console.log("hello")
}
$('#event-on-keyup').keyup(function(){
    hello()
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
<input type="text" id="event-on-keyup">
0 голосов
/ 29 августа 2012
jQuery.fn.make_me_red = function() {
    alert($(this).attr('id'));
    $(this).siblings("#hello").toggle();
}
$("#user_button").click(function(){
    //$(this).siblings(".hello").make_me_red(); 
    $(this).make_me_red(); 
    $(this).addClass("active");
});
​

Объявление функции и обратный вызов в jQuery .

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...