jquery removeAttr无法正常工作

时间:2012-01-17 21:14:26

标签: jquery drop-down-menu attr

您好我正在尝试使用名称为ufd的自动完成下拉列表插件。 无论如何,我有下拉列表,我想在codebehind click_event上获得这个选定的值(或文本)。 如果我可以从下拉列表中删除所有选定的attr并将选定的attr添加到所选选项,这将有效。但是这个removeAttr不起作用:(请帮助我。

       $(function () {
        var element = $("#DropDownList1");
        $(element).change(function () {
        $(element).find('option').removeAttr('selected'); //this is not working
        $(element + "option[value=" + $(element).val() + "]").attr("selected", "selected");
        });
       });

    <asp:DropDownList ID="DropDownList1" runat="server">
    </asp:DropDownList>
    <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />

代码隐藏:

    protected void Page_Load(object sender, EventArgs e)
    {
        using (TalepService tService = new TalepService())
        {
            DropDownList1.DataSource = tService.ddlTalepDurumDoldur();
            DropDownList1.DataTextField = "talepDurumu";
            DropDownList1.DataValueField = "talepDurumID";
            DropDownList1.DataBind();
        }
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        string text = DropDownList1.SelectedItem.Text;
        string value = DropDownList1.SelectedValue;
    }

4 个答案:

答案 0 :(得分:1)

您正在从jQuery对象创建jQuery对象,这在这一行上存在问题(我假设):

$(element + "option[value=" + $(element).val() + "]").attr("selected", "selected");

因为element是一个jQuery对象(关键字,对象),并且您要向该对象添加一个字符串。

试试这个:

$(function () {
    var element = $("#DropDownList1");
    element.change(function () {
        var theVal = element.val();//get the current value since it will be removed on the next line
        element.find('option').removeAttr('selected'); //this is not working
        element.find("option[value=" + theVal + "]").attr("selected", "selected");
    });
});

以下是演示:http://jsfiddle.net/LjhwW/1/

在创建这个演示时,我意识到了“我不是我”(在评论中)。为什么要手动更改change事件的选定选项元素,浏览器无论如何都会这样做。

答案 1 :(得分:1)

element已经是一个jQuery对象,因此您不必使用$()。通常,如果它是jQuery对象,我们将前缀$添加到变量名称。试试这个。

$(function () {
    var $element = $("#DropDownList1");
    $element.change(function () {
       var val = this.value;
       $element.find('option').removeAttr('selected')
       .filter("[value=" + val + "]")
       .attr("selected", "selected");
    });
});

答案 2 :(得分:0)

使用jquery更改select的选定值的正确方法是设置其值。

$("#DropDownList1").val("new-selected-value")

答案 3 :(得分:0)

selectedIndex的{​​{1}}属性设置为-1以清除所选项目。

相关问题