-1

jQuery を使用して、クリックしたコントロール (ラジオボタン) の ID を取得しようとしています。私はこの質問を読み、そこからほとんどすべてを試しました:

alert($(this).get(0).id);
alert($(this).id);
alert($(this).attr('id'));
alert(this.id);

しかし、私はいつも得ています:Undefined

私は自分が間違っていることを理解していません。

更新しました:

Radiobuttons は、C# によってコード ビハインドで動的に生成されます。

controlToReturn = new RadioButton
                    {
                        ID = controlId
                    };
                    ((RadioButton)controlToReturn).Text = text;
                    ((RadioButton)controlToReturn).Checked = Convert.ToBoolean(Convert.ToInt32(value));
                    ((RadioButton)controlToReturn).GroupName = groupName;
                    ((RadioButton)controlToReturn).CssClass = cssClass;
                    ((RadioButton)controlToReturn).Attributes.Add("runat", "server");
                    ((RadioButton)controlToReturn).Attributes.Add("onclick", "Show();");

ASPX での機能:

<script type="text/javascript" language="javascript">
function Show() {

             if ($(this).cheked = true) {

                 console.log(this);
                 alert($(this).get(0).id);
                 alert($(this).id);
                 alert($(this).attr('id'));
                 alert(this.id);               
             }        
         }
     </script>

ラジオボタンにIDがあることはわかっています。生成されたHTMLを確認しました。

4

3 に答える 3

3

あなたの問題はthis、関数内にコンテキストがなく、実際にはwindowそれ自体です。

コンテキストを引数として提供するには、両方の出力 html を変更する必要があります。

 ((RadioButton)controlToReturn).Attributes.Add("onclick", "Show(this);");

関数を変更しますShow

function Show(el) {
    /* for jQuery use $(el) */
    if(el.checked) {
        alert(el.id);
    }
}      
于 2012-11-22T20:24:04.680 に答える
2

C#:

((RadioButton)controlToReturn).Attributes.Add("onclick", "Show(this);");

JavaScript:

function Show(radio) {
    if (radio.checked) {
        alert(radio.id);               
    }        
}
于 2012-11-22T20:20:36.133 に答える
1

クリック リスナーをアタッチして ID を通知するには、コードは次のようになります。

​$(function () {
    $("input[type='radio']").on("click", function () {
        alert(this.id);            
    });
});​

実際のデモ: http://jsfiddle.net/SSBnV/1/

于 2012-11-22T20:05:52.667 に答える