2011-06-03 118 views
0

我剛在過去幾天開始使用jQuery。我喜歡它使功能變得簡單。不過,因爲我對使用JavaScript很陌生,所以我一直使用一個函數來打一個路障。如何在jQuery中傳遞變量

我試圖將幾個函數綁定在一起,但我不確定是否按照正確的順序執行它。我想要的是從選擇器href='#from=xxxxx&to=xxxxx'中獲取變量,其中xxxxx是使用PHP從數據庫打印出來的值。

然後創建一個DOM窗口來顯示一個表單並將這些值插入到隱藏的輸入字段中。我一直在試圖找出一種方法將這些變量從鏈接傳遞給表單。

這裏是我的腳本:

<html> 
<head> 
    <script src="http://code.jquery.com/jquery-latest.js"></script> 
<script src="http://swip.codylindley.com/jquery.DOMWindow.js"></script> 
</head> 
<body> 
<div id="msgBox" style="display:none"></div> 
<?php $from="0"; $to="0"; 
for ($x=1; $x<=4; $x++){ $from++; $to++; ?> 
<a href="#from=<?php echo $from;?>&to=<?php echo $to;?>" class="foo">user<?php echo $x;?></a><br> 
<?php } ?> 
<script type="text/javascript"> 
     $("#msgBox").append("<form id='myForm' method='post' action='index.php'><div style='border:1px solid #cc0; width:300px;'><input type='hidden' value='<?php echo $from;?>'><input type='hidden' value='<?php echo $to;?>'>subject:<input type='text' name='subject'><br>message:<textarea class='mbox' name='msg'></textarea><br><input type='submit' value='submit'></div></form>"); 
     $('.foo').click(function(){ 
      $.openDOMWindow({ 
       windowSourceID:'#msgBox', 
       height:135, 
       width:300, 
       overlay:0, 
       positionType:'anchoredSingleWindow', 
       windowBGColor:'#f9f5f5', 
       anchoredSelector:'.foo', 
       positionLeft:200, 
       positionTop:150 
      }); 
        $("#msgBox").trigger(); 
      return false; 
    }); 
</script></body></html> 

回答

0

在處理每一個環節上的click事件,你可以到達目標鏈接的引用,並從href屬性提取值,然後設置的值隱藏在窗體中的字段。

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

var href = $(this).attr('href'); // will contain the string "#from=0&to=0" 

var from,to = ... // extarct from string by splitting by & or using url parse library 

$('#msgBox').find("input[name='from']").val(from); 
$('#msgBox').find("input[name='to']").val(to); 

// rest of code... 

}); 
+0

嗨,謝謝你的迴應,我如何將這些值傳遞給表格壽。我有點能夠分開之前的值。還有其他的代碼可能會告訴你我正在嘗試做什麼。 – Michael 2011-06-03 23:57:42

+0

再次抱歉。知道了,只需再讀幾遍 – Michael 2011-06-03 23:59:57