2013-07-25 185 views
0

我想要做到以下幾點: 2 div,clickable返回div的「值」。這是通過在div上創建(內部)get_value函數來實現的。訪問自定義內部函數JQueryFunction

但我真正想要的是有一個按鈕,通過調用get_value函數讀取div的值。例如,請參閱以下代碼。

不幸的是我不能得到它的工作....

我曾試圖讓全球價值觀,但隨即又被覆蓋......

任何線索?

<html xmlns="http://www.w3.org/1999/xhtml"> 
<head runat="server"> 
    <title></title> 
    <script src="Js/jquery-1.10.2.js" type="text/javascript"></script> 
    <script> 


     $(document).ready(function() { 
      initdiv("a", 10) 
     }); 
     $(document).ready(function() { 
      initdiv("b", 20) 
     }); 

     function initdiv(id, value) { 
      function get_value() { 
       return value; 
      }; 

      $("#" + id).click(function() { 
       alert(get_value()); 
      }); 
     } 

     function getFoo() { 
      var obj = $("#a"); 
      alert(obj.get_value()); 
     } 
    </script> 
</head> 
<body> 
    <form id="form2" runat="server"> 
    <div id="a"> 
     foo 
    </div> 
    <div id="b"> 
     bar 
    </div> 
    <input type="button" onclick="getFoo();" value="click me and get the value of DIV 'foo'" /> 
    </form> 
</body> 
</html> 
+0

爲什麼不把值在DOM和檢索它的點擊? –

回答

0

這是unnecesary寫函數每次執行init_div功能。此功能也將這樣做對你:

$('div').click(function() { 

    alert($(this).text()); //or '.html()' 

}); 

對於按鈕,就可以用同樣的方法:

$('button').click(function() { 

    alert($('div#a').text()); //or '.html()' 

}); 

如果你想讓它更一般的,你可以使用這個:

jQuery的

function get_value(selector) { 

    alert($(selector).text()); 

} 

$(document).ready(function() { 

    $('div').click(function() { 

     get_value(this); 

    }); 

}); 

HTML

<input type="button" onclick="get_value('.foo')" value="click me and get the value of DIV 'foo'" /> 

工作演示:http://jsfiddle.net/yp8V4/

+0

你的第一點,我知道,它只是我的dot.net代碼的簡化版本,用於呈現具有不同設置的多個webcontrols :) 您指的是.Text()的JQuery函數,但是我想添加一些變量提交給呈現的控件。 那些添加的變量是這些我想可以使用/從其他JScript函數讀取。 –