【问题标题】:Select tag not firing the event handler选择标签不触发事件处理程序
【发布时间】:2023-02-05 05:39:49
【问题描述】:

对于一个项目,我使用的是 vanilla HTML/CSS/JS。我试图隐藏页面中的所有项目,在选择标签中选择默认选项,仅显示具有所选 ID 的元素并使用下拉菜单选择时间段并仅显示该特定元素。

在我的文件中,我以这种方式构建了函数。我有一个控制台日志,以确保查看代码是否运行。它只输出日志一次,无论我在过滤器中选择什么都不会触发。我认为问题出在我的事件处理程序没有触发,但我确信我遵循了示例。这里可能是什么问题?

var day = document.getElementById("day");
var week = document.getElementById("week");
var month = document.getElementById("month");

period = document.getElementById("filter");
function loadPost(period) {
    // Hide all posts
    day.style.display = "none";
    week.style.display = "none";
    month.style.display = "none";
    switch (period) {
        case day:
            showDay();
            break;
        case week:
            showWeek();
            break;
        case month:
            showMonth();
            break;
    } 
    console.log(period);
}
function showDay() {
    day.style.display = "block";
}
function showWeek() {
    week.style.display = "block";
}
function showMonth() {
    month.style.display = "block";
}
period.addEventListener("change", loadPost(period.value));
        <div class="most-popular">
            <h1>Most Popular</h1>
            <label for="most-popular-filter">Filter:</label>
            <select name="most-popular-filter" id="filter">
                <option value="day">Day</option>
                <option value="week">Week</option>
                <option value="month">Month</option>
            </select>
            <div class="content-box" id="day">
                <img src="images/placeholder.png" alt="most-popular">
                <h2>Most Popular 1</h2>
                <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Quisquam, quae.</p>
            </div>
            <div class="content-box" id="week">
                <img src="images/placeholder.png" alt="most-popular">
                <h2>Most Popular 2</h2>
                <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Quisquam, quae.</p>
            </div>
            <div class="content-box" id="month">
                <img src="images/placeholder.png" alt="most-popular">
                <h2>Most Popular 3</h2>
                <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Quisquam, quae.</p>
            </div>      
        </div>

【问题讨论】:

    标签: javascript html css


    【解决方案1】:

    使用回调函数并在内部调用其他函数:

    period.addEventListener("change", ()=&gt;loadPost(period.value));

    【讨论】:

    • 为什么会这样?箭头运算符有什么用,为什么我的实现有问题?
    • period.addEventListener("change", function(){loadPost(period.value)});它也可以工作,但是在箭头函数的情况下,如果有一个外部函数(案例类型),则外部函数的“this”实例将不适用于箭头函数。
    猜你喜欢
    • 1970-01-01
    • 2012-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-15
    • 2011-09-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多