The problem that a tag cannot call js method

一个新手
Release: 2023-03-16 06:10:01
Original
2143 people have browsed it

When we do background deletion, when you click to delete a tag, you want a friendly prompt box to pop up! For example:

#How should the code be written? Like this?


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <script>
        window.onload=function () {            
            function confirmdelete(id) {                
                return  window.confirm("你确定要删除吗?");
            }
        }    
   </script>
</head>
<body>

</body>
<?php   
echo "<a onclick=&#39;confirmdelete(2)&#39;>删除</a>";?>
Copy after login

You will find that such an error occurs:

The function is not used? It shouldn't be, haven't I already called it in php?

Note:

People who have written front-end must know that this method is executed after all pages are loaded, so the problem arises, PHP The execution order is before js, so when php is executed, it is found that the method in the a tag does not exist, because js has not been executed at this moment, so it causes the php a tag to call js and there is no response. .

Then the code becomes like this?


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <script>            
        function confirmdelete(id) {                
        return  window.confirm("你确定要删除吗?");
            }    
   </script>
</head>
<body>
</body>
<?php   
echo "<a onclick=&#39;return confirmdelete(2)&#39;>删除</a>";?>
Copy after login

The result is successful execution! Some people say it's wrong. Didn't you say that the execution order of php should precede js? This is no different from the above.

Then you should pay attention at this moment. After the window.onload method constraint, the js is executed last. Then when you remove this constraint, you will find that this function

is just A statement, in js, for functions that are only declared, it will be compiled first, so when the a tag of php is executed at this time, because the function it wants to call has been pre-compiled, it can be called.

The above is the detailed content of The problem that a tag cannot call js method. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template