我正在尝试使用javascript以编程方式填充html选择框。 我发现虽然我的代码可以工作,但jquery移动会干扰选择框中显示的内容。 我正在设置所选选项,该选项正在工作,但选择框中显示的值是错误的值。 它与我最初填写的内容和 html 没有变化。
我正在链接:"http://code.jquery.com/mobile/1.3.0/jquery.mobile-1.3.0.min.css"。有没有办法绕过jquery?我不能只是删除jquery css。这会破坏我网站上的所有内容,我没有时间重做所有内容。
这是问题的一个小问题:http://jsfiddle.net/RjXRB/1/
这是我的代码供参考:
这是我填充选择框的 javascript 函数:
function printCartList(newCart){
// newCart is an optional parameter. Check to see if it is given.
newCart = newCart ? newCart : "a_new_cart_was_not_provided_12345abcde";
// Create a cart list from the stored cookie if it exists, otherwise create a new one.
if($.cookie("carts") != null){
carts = JSON.parse($.cookie("carts"));
}
else{
selectOption = new Object();
selectOption.value = "newuniquecartid12345abcde";
selectOption.html = "***New Cart***";
carts = new Object();
carts.size = 1;
carts.option = new Array();
carts.option[0] = selectOption;
}
// Get the select box
var select = document.getElementById("select_cart");
// Get the number of options in the select box.
var length = select.options.length;
// Remove all of the options in the select box.
while(select.options.length > 0){
select.remove(0);
}
// If there is a new cart, add it to the cart.
if(newCart != "a_new_cart_was_not_provided_12345abcde"){
selectOption = new Object();
selectOption.value = newCart;
selectOption.html = newCart;
carts.option[carts.size] = selectOption;
carts.size++;
}
// Save the cart in a cookie
$.cookie("carts",JSON.stringify(carts));
// Populate the select box
for(var i = 0; i < carts.size; i++){
var opt = document.createElement('option');
opt.value = carts.option[i].value;
opt.innerHTML = carts.option[i].html;
if($.cookie("activeCart") == carts.option[i].value && newCart != "a_new_cart_was_not_provided_12345abcde"){
// Set the selected value
alert(carts.option[i].value);
opt.selected = true;
// I tried changing the value of a p tag inside the default option, but that didn't work
document.getElementById("selectHTML").innerHTML = carts.option[i].html;
}
if(opt.value == "dd"){alert("hi");};
select.appendChild(opt);
}
}
这是我的网页:
<form method="POST" name="cartSelectForm" action="home.php">
<select name="cartList" id="select_cart" data-mini="true" onchange="submitCartForm()" data-icon="false">
<option value="newuniquecartid1234567890"><p id="selectHTML">*** New Cart ***</p></option>
</select>
</form>
任何帮助将不胜感激。
我知道这个问题已经有一个月了,但我偶然发现了它,因为我遇到了完全相同的问题。我最终通过这样做修复了它:
以编程方式设置值后,我手动触发了该选择框上的更改事件。我想它迫使jQuery移动更新与该元素相关的所有增强标记。有点烦人,但幸运的是很容易解决。
$("#country").val("US");
$("#country").change();
希望对某人有所帮助。