简体   繁体   中英

Using Jquery to pass a variable into part of a link

I am working with dynamics and I am trying to pull in a variable from the form and use it to create a dynamic URL Here is my code:

<html>
  <head>
    <meta charset="utf-8">
    <script src="new_/jquery.js"></script>

    <script>
      $( document ).ready(function() {
        var $productid = attr("src",parent.window.Xrm.Page.getAttribute('new_productid').getValue());
      });
    </script>
  </head>
  <body style="word-wrap: break-word;">
    <div style="align: center;">
      <script type="text/javascript">
        document.write('<a href="http://www.mywebsite.com/products/'+productid+'">Link to some site</a>');
      </script>
    </div>
  </body>
</html>

Can anyone see what I am doing wrong?

you have 3 problems:

  1. $productid vs productid
  2. $productid is declared inside the callback function so is not in the same scope as your document.write call
  3. Even if $productid was in global scope your document.write call will more than likely happen before your $(document).ready callback so $productid will still not contain the value you expect.

So do your js work inside the ready callback, and put a placeholder anchor in your html that you can change once it is ready

HTML

<div style="align: center;">
  <a href="#" id="linkToChange">Some text</a>
</div>

JS

$( document ).ready(function() {
    var $productid = attr("src",parent.window.
                                Xrm.Page.
                                getAttribute('new_productid').getValue());
    $("#linkToChange").attr("href","http://www.mywebsite.com/products/'+$productid);
});

Also not sure what the function attr you are calling is, as you do not define it anywhere so you are more than likely getting an error for this as well

Your script is running before the variable is even declared, you declare the var in the jQuery ready() function, that is occuring AFTER that script block is executed. Move your js script to a function and have it called after the var is declared in the ready() function.

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