两个javascript动作"在两个不同页面的一个函数中


Two javascript "actions" inside one function in two different pages

我试图在custom.js文件中使用以下代码修改几个选择框。每个ID都在不同的页面中我在footer。php中使用的代码如下:

<script>
    var selectFunction = function() {
    document.getElementById('ofae').options[0].text = 'Artists';
    };
    var selectFunctionn = function() {
    document.getElementById('ofav').options[0].text = 'Artists';
    }; 
</script>

:

<?php
    // without if statement
    echo '<script type="text/javascript">  $(function(){  selectFunction();selectFunctionn(); }); </script>';
    ?>

问题是,只有其中一个得到执行,当我在第2页,第一个值是NULL,它不执行其余的代码。

测试文件test.php,代码如下:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Test php echo script</title>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
    </head>
    <body>
        <select id="ofav">
            <option value="">o1</option>
            <option value="">o2</option>
            <option value="">o3</option>
            <option value="">o4</option>
            <option value="">o5</option>
        </select>
        <select id="ofae">
            <option value="">o1</option>
            <option value="">o2</option>
            <option value="">o3</option>
            <option value="">o4</option>
            <option value="">o5</option>
        </select>
        <script>
        var selectFunction = function() {
        document.getElementById('ofav').options[0].text = 'Artists';
        document.getElementById('ofae').options[0].text = 'Artists';
        }
        </script>
        <?php
        // without if statement
        echo '<script type="text/javascript">  $(function(){  selectFunction();  }); </script>';
        ?>
    </body>
</html>

没问题!

检查:

  • 如果没有输入错误
  • 如果有两个<select>

像这样修改你的函数,它将工作

var selectFunction = function() {
    if(document.getElementById('ofae') != null){
         document.getElementById('ofae').options[0].text = 'Artists';
    }
    else if(document.getElementById('ofav') != null){
         document.getElementById('ofav').options[0].text = 'Artists';
    }
}; 

我希望这将解决你的问题