简体   繁体   中英

Not able to call a JavaScript function from PHP code?

How do I call a JavaScript function from href tag in html? I've created a few tabs and when a user clicks on one of them the href along with JavaScript function should get called.

<?php if($order == 1){ ?>
<li class="cat-one">
    <a href="javascript:void(0)" onclick="loadProducts(<?php echo $categoryId ?>)"> 
        <?php echo $categoryName ?> 
    </a>
</li>
<?php } ?>

This is my JavaScript:

function loadProducts($categoryId)
{
    alert("Hello World!");
    return false;
}

Why doesn't the alert trigger in my function? I am running 2 jQueries on the same page.

如果您尝试这样做怎么办:

<a href="#" onclick="loadProducts(<?php echo $categoryId ?>); return false;"> 

Try:

<script type="javascript" >
function loadProducts(categoryId)
{
alert("Hello World!" + categoryId);
return false;
}

</script>

And also:

<a href="#" onclick="loadProducts(<?php echo $categoryId ?>); return false;" > 
  <?php echo $categoryName ?> 
</a>

I just checked the JavaScript, you make a mistake while declaring script tag, the correct code is below

<script type="text/javascript" >
function loadProducts($categoryId)
{
alert("Hello World!");
return false;
}
</script> 

From your script above I really don't see nothing wrong with the JavaScript. Try debugging your PHP first to see if the expected value like ($categoryId) is exactly what you expect to be.

Your are missing something also from the script tag

<script type="text/javascript">
// Your script goes here... 
</script>

May be your php script has some errors, Try this example also.

<html>
<body>
<script type= "text/javascript">
function loadProducts(catid){
    alert(""Hello World!"+catid);
    return false;
}
</script>


<?php if($order == 1){ ?>
<li class="cat-one">
    <a href="javascript:void(0)" onclick="loadProducts(<?php echo $categoryId ?>)"><?php echo $categoryName ?> </a>
</li> 

</body>
</html>

From what I can tell without actually running this code, you can fix a few semi-colons on lines 3 and 4, change the href, and put the parameter for loadProducts in quotes. Try this:

<?php if($order == 1){ ?>
<li class="cat-one">
    <a href="#" onclick="loadProducts('<?php echo $categoryId; ?>')"> 
        <?php echo $categoryName; ?> 
    </a>
</li>
<?php } ?>

Let me know if it works out for you.

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