簡體   English   中英

Javascript-如何最小化此代碼示例?

[英]Javascript - how do I minimise this code example?

一個快速的問題。

目前,我在頁面上有12個鏈接,以及單擊每個按鈕時運行的12個相應的javascript代碼。

我知道100%必須有一種具有1個javascript代碼和將變量傳遞給它的鏈接的方法,因此我不必具有12個不同的代碼。

例如。 這是我當前正在使用的鏈接:

<a href="#" id="button1">Anatomical Pathology</a>

單擊鏈接時運行的Javascript函數將php腳本中的html加載到div中,該div先前定義為level2:

$('#button1').click(function() {
    level2.load("http://hello/script.php?url=poodles");
}); 

我真正想做的是帶有以下鏈接的內容:

<a href="#" id="button1" passurl="poodles">Anatomical Pathology</a>

函數是這樣的,所以我只需要1函數而不是12:

$('#button1').click(function() {
    level2.load("http://hello/script.php?url=' + passurl + '");
}); 

如何將鏈接標記中的數據導入javascript,以及如何將此傳遞的變量添加到希望javascript提取數據的url中?

passurl不是標准屬性,您應該使用data-passurl

$('#button1').click(function() {
    var passurl = $(this).data('passurl'); // or $(this).attr('data-passurl');
    level2.load("http://hello/script.php?url=" + passurl);
}); 

你為什么不在那里利用你的哈希...

<a href="#/poodles" class="button">Anatomical Pathology</a>

在您的腳本中

$(".button").each(function() {
  // get the hash and extract the part we want store it in this enclosure
  var url = $(this).attr("href").replace(/^#\//, "");
  // create a click handler that loads the url
  $(this).click(function() {
    level2.load("http://hello/script.php?url=" + url);
  });
});

這也帶來了從中推斷的可能性,以便通過url傳遞的哈希也可以操作腳本加載...

您可以使用rel屬性(如果使用HTML5 Doctype,則可以使用任何data-attribute)來保存URL並將類添加到要執行回調的鏈接中。

<a href="#" class="button" rel="your-url">Anatomical Pathology</a>

您的回電:

$('a.button').click(function() {
    level2.load("http://hello/script.php?url=' + $(this).attr('rel') + '");
});

對於更可擴展的解決方案,您可以考慮為您的網址建立一個json結構:

var urls = [{
    "poodle":{
        "url":"http://hello/script.php?url=poodle",
        "someOtherData":"data"
    },
    "otherDog":{
        "url":"http://hello/script.php?url=otherDog",
        "someOtherData":"data"
    }
}];

您將在HTML元素中的某處存儲某種密鑰:

<a href="#" rel="poodle">Anatomical Pathology</a>

然后,您可以在功能代碼中利用此數據結構:

$('a').click(function () {
    var key = $(this).attr('rel');
    level2.load(urls[key].url);
});

根據Stuie,將類添加到鏈接中,以便您可以一次將它們全部定位。 但是,我認為沒有必要弄混哈希值,也不會添加任何click事件。 只需委托一次,您就可以完成:

<div id="wrapper">
  <a href="poodles" class="button">Poodles</a>
  <a href="schnausers" class= "button">Schnausers</a>
</div>

和JS:

$('#wrapper').delegate('a.button', 'click', function(e) {
  e.preventDefault();
  var passurl = $(this).attr("href");
  level2.load("http://hello/script.php?url=" + passurl); // assuming "level2" is valid from elsewhere  
});

在有“ #wrapper”的地方,您將指定任何唯一選擇器,該選擇器是所有鏈接的祖先。 它是一個偵聽其中的a.button元素的單擊的元素。

暫無
暫無

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

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