开发者

PHP variable inside a javascript function

开发者 https://www.devze.com 2022-12-15 14:14 出处:网络
I\'m attempting to put a php variable inside a javascript function and having no luck, here\'s what I got

I'm attempting to put a php variable inside a javascript function and having no luck, here's what I got

<a class="code" href="javascript:void(0);"
   onclick="javascript:if(window.dd && 开发者_StackOverflowdd.elements) 
   d.elements.name1.moveTo(<? echo "$xpos"; ?>, <? echo "$ypos"; ?>);
   return false;">
name1.moveTo(name1.x-20, name1.y+7);</a>

`

the moveTo() function works perfectly when I send it a javascript variable or simple numbers.

the reason its in a php variable at all is because I need the xpos to be inside a session variable to be accessed in other places. Afterwards I assign it as follows

$_SESSION['productcheck']['x'] = $xpos;

I'm kinda new to this, if you haven't already noticed, Thank you ahead of time :)


try not putting double quotes.

echo $xpos;


This is just to clarify, but you seem to have a typo (d should be dd). Corrected:

<a class="code" href="javascript:void(0);"
   onclick="return (function () {
       if(window.dd && dd.elements) 
           dd.elements.name1.moveTo(<? echo $xpos; ?>, <? echo $ypos; ?>);
       return false; 
    })()"
>
    name1.moveTo(name1.x-20, name1.y+7);
</a>

Some issues:

  • You don't need PHP variable interrpolation, $xpos by itself is fine
  • onclick should have only one expression that returns false, so you'd ideally wrap it in a function elsewhere. Here I used an anonymous one

Also, onclick need not start with 'javascript:, since it already is implicitly so.


My guess would that xpos and ypos are not in scope at the time that part of the page is processed.

Scope refers to the enclosing braces. for example the following will not work

$xpos = 100;

function printx(){
  echo $xpos; // enclosing quotes not required
}

// call the function
printx();

Nothing will be printed

to fix it use the following

$xpos = 100;

function printx(){
  global $xpos;
  echo $xpos; // enclosing quotes not required
}

// call the function
printx();

this would then print 100

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号