JS函数永远不会被调用,但其他函数会被调用



我的JSP文件上有以下选择:

<select id="order-select">
<option value="Lowest price" onclick="sortLowestPrice()"><spring:message code="list.lowest"/></option>
<option value="Highest price" onclick="sortHighestPrice()"><spring:message code="list.highest"/></option>
</select>   

事实证明,我从来没有调用过sortLowestPrice((或sortHighestPrice((。 我知道我的JS可以工作,因为它上的其他函数在同一个JSP中被调用并且它们工作正常。

下面是其中一个函数:

function sortHighestPrice() {
console.log("im here");
var publications = document.querySelectorAll(".polaroid-property");
var sort = [];
var father = document.getElementById("publications");
var i, j, k;
var max = null;
while (father.firstChild) {
father.removeChild(father.firstChild);
}
for(i = 0; i < publications.length; i++){
max = null;
for(j = 0; j < publications.length; j++){
if(publications[j].getAttribute("visited") != "true"){
var price = parseInt(publications[j].getElementsByClassName("price-tag")[0].innerHTML.substring(1));
if(price > max || max == null){
max = price;
k = j;
}
}
}
sort.push(k);
publications[k].setAttribute("visited",true);
}
for(i = 0; i < sort.length; i++){
publications[i].setAttribute("visited",false);
father.appendChild(publications[sort[i]]);
}
}

我从来没有在浏览器日志上得到"im here"。

与其尝试侦听每个<option>上的单击事件,不如侦听父<select>标记上的更改事件,并从函数内的 DOM 事件对象中检索所选选项的值。见下文:

function sortHighestPrice(e) {
var optionValue = e.target.value;
}
<select onchange="sortHighestPrice(event)" id="order-select">
<option value="Lowest price" onclick="sortLowestPrice()">
<spring:message code="list.lowest"/>
option1
</option>
<option value="Highest price"         onclick="sortHighestPrice()">
<spring:message code="list.highest"/>
option2
</option>
</select>

希望这有帮助!

听起来您的浏览器不支持单击选项元素。尝试使用其他元素类型,例如按钮(即保证点击支持的内容(

这是我在使用chrome时遇到的问题。

你可以在w3schools上看到option标签不支持onSelect()onClick()

关于这个 Stackoverflow 问题的更多详细信息概述了另一种方法,正如我上面的评论所提到的。

最新更新