2016-04-25 61 views
3

我使用這個JavaScript編輯URL進行排序在WordPress由無編輯插件生成一個列表:的Javascript在頁面重載運行

<script type="text/javascript"> 
var sortRegex = /\[sort_by\]=\w*/; 
function priceHighZ() { 
    location.href = location.href.replace('[sort_order]=ASC', '[sort_order]=DESC').replace(sortRegex, '[sort_by]=price'); 
} 
function priceLowZ() { 
    location.href = location.href.replace('[sort_order]=DESC', '[sort_order]=ASC').replace(sortRegex, '[sort_by]=price'); 
} 
function dateHighZ() { 
    location.href = location.href.replace('[sort_order]=ASC', '[sort_order]=DESC').replace(sortRegex, '[sort_by]=date'); 
} 
document.addEventListener('DOMContentLoaded', function() { 
    document.getElementById('priceHighZ').addEventListener('click', priceHighZ); 
    document.getElementById('priceLowZ').addEventListener('click', priceLowZ); 
    document.getElementById('dateHighZ').addEventListener('click', dateHighZ); 
}); 
</script> 

它只有一次在頁面加載的第一次工作,然後重新加載頁面。它在第一次加載時不起作用。

DOMContentLoaded存在問題,這可能會導致此工作只有一次頁面重新加載?

我已經looked at this但不知道如何將這個例子應用到我上面的代碼。

回答

1

您可以使用jQuery .ready()事件來確保在腳本執行之前加載DOM(如鏈接示例中所示)。但在wordpress中,您使用jQuery而不是別名$。使用別名$與WordPress是可能的,例如增加var $ = jQuery.noConflict();

<script type="text/javascript"> 

var $ = jQuery.noConflict(); 

$(document).ready(function() { 

    var sortRegex = /\[sort_by\]=\w*/; 
    function priceHighZ() { 
     location.href = location.href.replace('[sort_order]=ASC', '[sort_order]=DESC').replace(sortRegex, '[sort_by]=price'); 
    } 
    function priceLowZ() { 
     location.href = location.href.replace('[sort_order]=DESC', '[sort_order]=ASC').replace(sortRegex, '[sort_by]=price'); 
    } 
    function dateHighZ() { 
     location.href = location.href.replace('[sort_order]=ASC', '[sort_order]=DESC').replace(sortRegex, '[sort_by]=date'); 
    } 
    document.addEventListener('DOMContentLoaded', function() { 
     document.getElementById('priceHighZ').addEventListener('click', priceHighZ); 
     document.getElementById('priceLowZ').addEventListener('click', priceLowZ); 
     document.getElementById('dateHighZ').addEventListener('click', dateHighZ); 
    }); 

}); 

</script> 

您可以使用jQuery的語法,而不是純JavaScript的更換,例如:通過$('#dateHighZ')…
document.getElementById('dateHighZ')…取代它。

+0

嗨機會,我嘗試了上面的例子,但JavaScript是仍以同樣的方式工作,即只能在重新加載頁面時工作:/關於它可能是什麼的任何想法? – GT22

1

確保您與點擊事件綁定的Id不以異步方式加載到DOM中。

+0

嗨,我是JavaScript新手@cris_dpa我可以在哪裏瞭解更多關於此? – GT22

1

這聽起來像是你的JavaScript正在加載頁面之前運行。但是當刷新頁面從本地加載並且頁面/元素在腳本之前已準備就緒時。據MDN:當最初的HTML文檔 被完全加載和分析

的DOMContentLoaded事件被觸發,而無需等待樣式表, 圖片和子框架完成加載。一個非常不同的事件 - 負載 - 只應該用於檢測完全加載頁面

給它這樣的

document.addEventListener('load', function() { 
    ... 
} 
+0

請參閱上面的代碼示例。我在代碼中使用了'document.addEventListener('DOMContentLoaded',function(){' – GT22

+0

您是否嘗試過'load'而不是'DOMContentLoaded'如上所述? – cmlonder

+0

對不起,我誤解了你的評論。在那裏加載而不是DOMContentLoaded。 – GT22