[英]Defining a single jQuery function for separate DOM elements
我有幾個jQuery click函數-每個函數都附加到一個不同的DOM元素,並且做的事情略有不同...
例如,一個打開和關閉字典,然后更改文本...
$(".dictionaryFlip").click(function(){
var link = $(this);
$(".dictionaryHolder").slideToggle('fast', function() {
if ($(this).is(":visible")) {
link.text("dictionary ON");
}
else {
link.text("dictionary OFF");
}
});
});
HTML
<div class="dictionaryHolder">
<div id="dictionaryHeading">
<span class="dictionaryTitle">中 文 詞 典</span>
<span class="dictionaryHeadings">Dialog</span>
<span class="dictionaryHeadings">Word Bank</span>
</div>
</div>
<p class="dictionaryFlip">toggle dictionary: off</p>
對於我想做的每件事,我都有單獨的單擊功能。
有沒有一種方法可以定義一個單擊函數並將其分配給不同的DOM元素? 然后,也許使用if else
邏輯來改變函數內部的工作?
謝謝!
澄清:
我有一個click
功能,可以:1)打開和關閉詞典,2)打開和關閉菜單,3)打開和關閉小地圖...等等...只是想通過組合所有代碼來減少代碼這些都變成了單擊功能
當然,您可以定義一個函數並將其用於多個HTML元素。 這是一種常見的模式,應盡可能使用!
var onclick = function(event) {
var $elem = $(this);
alert("Clicked!");
};
$("a").click(onclick);
$(".b").click(onclick);
$("#c").click(onclick);
// jQuery can select multiple elements in one selector
$("a, .b, #c").click(onclick);
您也可以使用data-
屬性將上下文信息存儲在元素上。 jQuery具有.data
函數(它只是.attr
的前綴代理),可讓您輕松設置和檢索元素上的鍵和值。 假設我們有一個人員列表,例如:
<section>
<div class="user" data-id="124124">
<h1>John Smith</h1>
<h3>Cupertino, San Franciso</h3>
</div>
</section>
現在,我們在.user
類上注冊一個點擊處理程序,並獲取用戶的ID:
var onclick = function(event) {
var $this = $(this), //Always good to cache your jQuery elements (if you use them more than once)
id = $this.data("id");
alert("User ID: " + id);
};
$(".user").click(onclick);
這是一個簡單的模式
function a(elem){
var link = $(elem);
$(".dictionaryHolder").slideToggle('fast', function() {
if (link.is(":visible")) {
link.text("dictionary ON");
}
else {
link.text("dictionary OFF");
}
});
}
$(".dictionaryFlip").click(function(){a(this);});
$(".anotherElement").click(function(){a(this);});
好吧,您可以執行以下操作:
var f = function() {
var $this = $(this);
if($this.hasClass('A')) { /* do something */ }
if($this.hasClass('B')) { /* do something else */ }
}
$('.selector').click(f);
在f函數中,您檢查一下clicked元素的類
並根據您的意願執行
為了獲得更好的性能,您只能為頁面分配一個事件偵聽器。 然后,使用event.target
來了解單擊了哪個部分以及該怎么做。
我會將每個動作放在單獨的函數中,以保持代碼可讀性。
我還建議您為每個需要點擊的項目使用唯一的ID。
$("body").click(function(event) {
switch(event.target.id) {
// call suitable action according to the id of clicked element
case 'dictionaryFlip':
flipDictionnary()
break;
case 'menuToggle':
toggleMenu()
break;
// other actions go here
}
});
function flipDictionnary() {
// code here
}
function toggleMenu() {
// code here
}
cf. 使用jQuery進行事件委派http://www.sitepoint.com/event-delegation-with-jquery/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.