简体   繁体   中英

How to pass a variable with in jquery

I just started using jQuery in the past few days. I love how it makes functions simple. However because I am very new to using Javascript, I keep hitting a road block with one function.

I am trying to bind a couple functions together, but I'm not sure if I am doing it in the right order. What I want it to do is get a variable from a selector href='#from=xxxxx&to=xxxxx' , with the xxxxx being a value printed out from a DB using PHP.

Then create a DOM window to display a form and insert those values into the hidden input fields. I have been stuck trying to figure out a way to pass those variables from the link to the form.

Here is my script:

<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>

In the handler for the click event on each link you can get a reference to the target link and extract the values from the href attribute and then set the values of the hidden fields in the form.

$('.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...

});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM