2015-10-23 48 views
2

我的頁面在單擊id =「yourgoal」單選按鈕後顯示一個div。我希望頁面只在第一次單擊「yourgoal」中的按鈕時滾動到該div。這是我正在使用的代碼。我不希望頁面在第一次點擊後滾動到div。僅在第一個單選按鈕上單擊滾動頁面單擊

$('input:radio[name="yourgoal"]').change(function() { 
       if ($('#calculations1').css('display') == 'none') { 
          $('html, body').animate({ 
          scrollTop: $("#scrollto").offset().top 
          }, 1500); 

        } 

問題是,它打破了我對.change()函數的其餘部分。我不想把所有的函數放在if和then之後,再放到else {}語句中,因爲這看起來像是大量的冗餘代碼(它也打破了它)?我該如何做一個簡單的if語句,它不會影響.change函數中其餘的動作?

也許有一個更簡單的解決方案,我超越了這個?

在此先感謝!

回答

2
$('input:radio[name="yourgoal"]').one('change', 
    function() { 
     if ($('#calculations1').css('display') == 'none') { 
      $('html, body').animate({ 
       scrollTop: $("#scrollto").offset().top 
      }, 1500); 
     } 
    } 
); 

我推薦使用一個。第一次事件觸發後,它會自動刪除。

如果您有更多代碼需要在第一次更改後需要保留,您可以使用事件命名空間並附加多個更改。

$('input:radio[name="yourgoal"]').one('change.firstChange', 
    function() { 
     if ($('#calculations1').css('display') == 'none') { 
      $('html, body').animate({ 
       scrollTop: $("#scrollto").offset().top 
      }, 1500); 
     } 
    } 
); 
$('input:radio[name="yourgoal"]').on('change.allChanges', 
    function() { 
     // All your other code that stays attached 
    } 
); 

編輯:好像一個不會因爲那是一個「事件將被連接到具有名稱yourgoal每個單選按鈕的工作,所以它會一次爲每個第一個單選按鈕點擊單獨滾動,但你可以做如果您只想在第一次選擇單選按鈕時進行滾動,而不是首次選擇所有共用您的名稱的單選按鈕。

小提琴:http://jsfiddle.net/31s3LLjL/3/

$('input:radio[name="yourgoal"]').on('change.firstChange', 
    function() { 
     $('input:radio[name="yourgoal"]').off('change.firstChange'); 
     $('html, body').animate({ 
      scrollTop: $("#scrollto").offset().top 
     }, 1500); 
    } 
); 
$('input:radio[name="yourgoal"]').on('change.allChanges', 
    function() { 
     // Other change stuff 
    } 
); 
+0

太棒了!所以對於其餘的變化,我真的需要使用:$('input:radio [name =「yourgoal」]')。on('change.allChanges',或者我可以保留原始的.change(function()我已經擁有的代碼?實際上,只是要測試。非常感謝! – JohnC

+0

@JohnC,不需要命名空間另一個。我只是爲了讓代碼更清楚每個事件的作用。 http://jsfiddle.net/31s3LLjL/4/ – AtheistP3ace

+1

它似乎是必要的。其餘的功能打破了我沒有使用你的「on('change.allChanges',」版本並保留我的舊.change(功能()。很高興知道!再次感謝 – JohnC

0

您可以使用event.stopImmediatePropagation(),以防止對特定事件訂閱回調的執行。

$('input:radio[name="yourgoal"]').one('change',function(event) { 
    event.stopImmediatePropagation(); 
    if ($('#calculations1').css('display') == 'none') { 
    $('html, body').animate({ 
     scrollTop: $("#scrollto").offset().top 
    }, 1500); 
    } 
}); 

只要確保您的代碼預先處理所有其他change處理程序定義。