簡體   English   中英

使用jQuery傳遞elements事件?

[英]Passing the elements event using jQuery?

我正在嘗試使用jQuery將元素“事件”傳遞到JavaScript函數單擊中。

排隊:
直接(內聯)執行此操作很容易。

<a href="#" onclick="ToggleMinimize('Hello World', event)">Click Me</a>


使用JQUERY:
但是如何使用jQuery來實現呢?

<script type="text/javascript">
<!--
    function ToggleMinimize(title, e) 
    {
        // ...various execution code would be here ... //
    }

    jQuery(window).load(function() {

        // How do I "get at" the "event" object for the element & pass it into the function definition?
        jQuery(".chatDialog-toggle-button").bind('click', ToggleMinimize);
    })
-->
</script>

提前謝謝你!

在許多其他人展示了有關將數據傳遞給事件函數的內容之后,有一種針對此的特定方法,您可以按照這種方式在每次綁定中傳遞完整的對象映射。

另外請記住,jQuery在接收事件對象之前對其進行了規范化,因此它有所不同,請參見: http : //api.jquery.com/category/events/event-object/

function ToggleMinimize(e) {
    // ...various execution code would be here ... //
    // e.data contains the data object map
    // e.data.msg == "Hello World"
}

jQuery(window).load(function() {       
    jQuery(".chatDialog-toggle-button").bind('click', {'msg': "Hello World"}, ToggleMinimize);
});

您不必這樣做,它已經是第一個參數,例如:

function ToggleMinimize(e) {
    // ...various execution code would be here ... //
}
jQuery(window).load(function() {       
    jQuery(".chatDialog-toggle-button").bind('click', ToggleMinimize);
});

如果您想通過一個標題,然后可以使用匿名函數,就像這樣:

function ToggleMinimize(title, e) {
  // ...various execution code would be here ... //
}
jQuery(window).load(function() {       
  jQuery(".chatDialog-toggle-button").click(function(e) {
    ToggleMinimize("some title", e);
  });
});

我個人將使用數據屬性,如下所示:

<a href="#" class="chatDialog-toggle-button" data-title"Hello World">Click Me</a>

然后像這樣訪問它:

function ToggleMinimize(e) {
  var title = jQuery(this).data("title");
}
jQuery(window).load(function() {       
    jQuery(".chatDialog-toggle-button").click(ToggleMinimize);
});

您可以發送執行ToggleMinimize()的匿名函數:

jQuery(window).load(function() {
    jQuery(".chatDialog-toggle-button").bind('click', function(e) {
          ToggleMinimize( "Hello World", e);
    });
})

或者您可以讓ToggleMinimize返回一個函數,以便可以將Hello World傳遞給它。

function ToggleMinimize(title) {
    return function(e){ alert(title); alert(e.target); }
}

jQuery(window).load(function() {
    jQuery(".chatDialog-toggle-button").bind('click', ToggleMinimize( "Hello World") );
})

您可以這樣操作:

$(document).ready(function() {
  $('.chatDialog-toggle-button').bind('click', function(event) {
      ToggleMinimize(event);
  });
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM