javascript事件数组

array of events javascript

本文关键字:数组 事件 javascript      更新时间:2024-02-07

我有一个Javascript数组,如下所示:

var fruits=['apple','orange','peach','strawberry','mango']

我想添加一个关于这些元素的事件,它将为我的数据库提供各种各样的内容。例如"苹果"会给我

<div class="apple">golden</div>
<div class="apple">granny</div>
<div class="apple">canada</div>

此外,我的数据库中没有关于芒果品种的任何信息,我想从数组的其他部分突出显示"芒果"。我已经创建了这样的类:

.black {
    color: black;
    pointer-events: none;
    cursor: default;
}
.couleur {
    color: blue;
}

我必须添加HTML代码吗?谢谢你的帮助,这只是我在stackoverflow上的第二篇文章,很抱歉出现了奇怪的代码示例。

好吧,由于这是您的第二篇文章,我假设您对web开发还比较陌生。欢迎

您的问题不太清楚您想要发生什么,所以我首先假设简单:我们将创建一个onclick事件,对php脚本进行AJAX调用(您标记了php,所以我假设您正在编写php脚本),然后在页面上的动态div中显示结果。

我将使用一些php脚本的替代样式,所以当你看到时不要害怕

if ($something):
    // do something
else:
    // do something else
endif;

首先,让我们设置我们的元素:

<?php
// Assume we already have the fruit categories stored in an array, $categories
// Display each fruit category on the page
foreach ($categories as $category) :
?>
    <div class='category' id='<?=$category?>'><?=$category?></div>
<?php
endforeach;
?>
<!-- empty placeholder div - this is where our results will go -->
<div id='results'></div>

这将显示我们希望在页面上启动的所有元素。如果您想根据类别类对这些元素进行样式设置,请直接进行。

接下来,我们需要编写一些javascript来确定onClick行为。为此,我们可以使用直接的javascript,也可以使用jQuery(这在今天非常流行——仔细阅读,并不难理解)。

<script type='text/javascript' language='javascript'>
    $('.category').click(function() {
        // grab the category (based on the id of the element) and send it to our background page
        var category = $(this).id();
        $.post('backgroundScript.php', 
            {
                type: category
            }, 
            function(data) {
                // print the results inside the #results div
                $('#results').html(data);
            }
        );
    });        
</script>

最后,我们需要一个后台脚本来处理数据并返回结果。

<?php
//backgroundScript.php
$type = $_POST['type'];
// pass $type in to the database and perform some joins to get the subcategories in an array,
// then present a list of subcategories
$subcategories = findSubCategoriesInDB($type);
if (count($subcategories)) {
    echo "<ul>";
    foreach ($subcategories as $subcat) {
        echo "<li>" . $subcat . "</li>";
    }
    echo "</ul>";
} else {
    echo "No subcategories were found for " . $type;
}