2009-05-29 72 views
0

下面的代碼產生jQuery選擇沒有jQuery的事件中工作

function (value) { 
    if (value === undefined) { 
     var elem = this[0]; 
     if (elem) { 
      if (jQuery.nodeName(elem, "option")) { 
       return (elem.attributes.value || {}).specified ? elem.value : elem.text; 
      } 
      if (jQuery.nodeName(elem, "select")) { 
       var index = elem.selectedIndex, values = [], options = elem.options, one = elem.type == "select-one"; 
       if (index < 0) { 
        return null; 
       } 
       for (var i = one ? index : 0, max = one ? index + 1 : options.length; i < max; i++) { 
        var option = options[i]; 
        if (option.selected) { 
         value = jQuery(option).val(); 
         if (one) { 
          return value; 
         } 
         values.push(value); 
        } 
       } 
       return values; 
      } 
      return (elem.value || "").replace(/\r/g, ""); 
     } 
     return undefined; 
    } 
    if (typeof value === "number") { 
     value += ""; 
    } 
    return this.each(function() {if (this.nodeType != 1) {return;}if (jQuery.isArray(value) && /radio|checkbox/.test(this.type)) {this.checked = jQuery.inArray(this.value, value) >= 0 || jQuery.inArray(this.name, value) >= 0;} else if (jQuery.nodeName(this, "select")) {var values = jQuery.makeArray(value);jQuery("option", this).each(function() {this.selected = jQuery.inArray(this.value, values) >= 0 || jQuery.inArray(this.text, values) >= 0;});if (!values.length) {this.selectedIndex = -1;}} else {this.value = value;}}); 
} 

當警報被調用。我期待看到「你好」。無論出於何種原因,我可以使用選擇器來觸發jQuery事件,但是當我嘗試使用該事件中的任何DOM元素時,它將失敗。有什麼想法嗎?

<asp:Content ID="indexContent" ContentPlaceHolderID="MainContent" runat="server"> 

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


      $("#myButton").click(function() { alert("clicked!"); alert($("#myHTML").val); }); 


     } 
    ); 
</script> 

    <h2><%= Html.Encode(ViewData["Message"]) %></h2> 
    <p> 
     To learn more about ASP.NET MVC visit <a href="http://asp.net/mvc" title="ASP.NET MVC Website">http://asp.net/mvc</a>. 
    </p> 
    <button id="myButton" style="height:50px; width:200px;" >Click Me!</button> 
    <div id="myHTML"> 
    hello 
    </div> 
</asp:Content> 

回答

4

$("#myHTML").val()應該工作。確保包含括號。

此外,爲了提醒DIV的內容,.text().html()會更好。

+0

:)非常感謝。我的第一個stackoverflow問題很弱!我身上的VB讓我錯過了父母。 – vonfeldj 2009-05-29 17:49:07