用Javascript设置选中的属性onClick

Setting selected atrribute onClick with Javascript

本文关键字:属性 onClick Javascript 设置      更新时间:2023-09-26

我的javascript技能不是最好的,但我最近一直在努力,我想做的一件事是为html选项标签设置属性。我在jfiddle上发布了这个项目,使它更容易看到。你可以在这里看到。我想我只是少了一行代码什么的。

我如何从选项2中删除选中的属性,并为选项1创建选中的属性?换句话说,当我打开'another-popup'时,选项1被选中,而不是选项2。

我建议您查看jsFiddle链接,但我也发布了关于这个问题的代码。更新链接的javascript:

function updateSelected(id, removeID, parentID) {
    document.getElementById(parentID).style.display = 'none';
    document.getElementById(id).setAttribute("selected","selected");
    document.getElementById(removeID).removeAttribute("selected")
}
html:

<a href="#box" rel="popup">Popup</a>
<div id="box" class="popup">
<a href="#another-box" rel="popup" onClick="updateSelected("1", "2", "box");">Another box</a>
</div>
<div id="another-box" class="popup">
<form>
    <select>
        <option id="1">option 1</option>
        <option id="2" selected>option 2</option>
    </select>
</form>
</div>

Thanks for the help

要更改选择的条目,您应该更改.selected 属性,而不是属性

document.getElementById(id).selected = true;

属性只设置控件的初始值,而属性设置当前值。

注意,也不需要从先前选择的元素中删除属性。这是自动发生的,因为(默认情况下)一次只能"选择"一个元素。

或者,将封闭的<select>上的.value属性设置为与所需的<option>元素的值相同。该值将为<option>元素上的value属性的值,如果没有value属性,则为包含的文本的值。

见http://jsfiddle.net/alnitak/C98Wc/

注意你的引号,试着用这个代替<a>标签:

<a href="#another-box" rel="popup" onClick="updateSelected('1', '2', 'box');">Another box</a>

不能在双引号内使用双引号

像这样:

document.getElementById(id).selected=1;//or true

,另一种方式是

document.getElementById(id).selected=0;//or false

@Alnitak -谢谢你的更正

为什么不一直使用jQuery呢?在双引号

内使用单引号

小提琴

<a href="#another-box" rel="popup" id="another" >Another box</a>

$(function() {
    $('a[rel*=popup]').leanModal({ top : 200, closeButton: ".popup-close" });       
    $("#another").on("click",function(e) {
        updateSelected("o1","box");
        return false; // cancel click - can be e.preventDefault() instead 
    });

});         
function updateSelected(id, parentID) {
    $("#"+parentID).css("display","none"); // or .hide()
    $("#"+id).prop("selected",true);
}