我有以下代码:

function $(id) {
    return document.getElementById(id);
}
var material = $("material");
var materialPrices = {"invalid": "from £800.00","1": "£1,200.00","2": "£800.00","3": "£800.00"};
var price = 0;
function update() {
    $(".block").animate( { backgroundColor: '#B5D8EA' }, 500);
    price = materialPrices[material.options[material.selectedIndex].value];
    document.getElementById('pprice').innerHTML = price;
}
material.onchange = update;


当从下拉选择框中选择一个值时,基本上在$(".block").animate( { backgroundColor: '#B5D8EA' }, 500);行中返回$(".block")为null。有人告诉我,这与以下功能有关:函数$(id),但不知道如何修改我的代码以使其全部正常工作,请有人帮忙,我的js很弱!!!

谢谢

最佳答案

..您在$符号上存在冲突。
$jQuery的快捷方式,您可以将该快捷方式覆盖为其他功能(document.getElementById)。糟糕的是,即使重新定义了jquery,也可以将其与$快捷方式一起使用。
解决方案是将函数重命名为其他名称:

function getById(id) {
     return document.getElementById(id);
}
var material = getById('material');


对jQuery对象使用完整的jQuery表示法:

  jQuery(".block").animate( { backgroundColor: '#B5D8EA' }, 500);


我的观点是,如果您使用jQuery,则可以很容易地通过id获得一个元素,而无需添加另一个函数来处理该问题。例如:

document.getElementById(someId) == $('#'+someId).get(0);

07-24 09:50
查看更多