如何为.onchange函数设置默认值并仍然保持“onchange”功能?

时间:2021-02-25 00:25:03

I have created a custom search application showing results of a user input. In the application I have included a way for the user to control the amount of results that display.

我创建了一个自定义搜索应用程序,显示用户输入的结果。在应用程序中,我为用户提供了一种控制显示结果量的方法。

HTML

<select id="countShow">
    <option selected="selected">10</option>
    <option>25</option>
    <option>50</option>
    <option>100</option>
</select>

jQuery

$("select").on('change', function () {
    $('#countShow').val(10);
    var str = "";
    $("select option:selected").each(function () {
    str = $(this).text();
    str = parseInt(str) - 1;
});
    $('div > #result:gt('+str+')').remove();
    console.log(str);
})

My console.log shows the original value as 10 when the page loads and I understand that it is waiting for the control to change.

我的console.log在页面加载时将原始值显示为10,并且我知道它正在等待控件更改。

I have tried adding the following before the function to create a default value:

我尝试在函数之前添加以下内容以创建默认值:

$('#countShow').val(10); //the value stays 10 and will not change on event
$('div > #result:gt(9)').remove(); //does the same as the first

1 个解决方案

#1


2  

you can call it on page load:

你可以在页面加载时调用它:

$(document).ready(function(){
  $("select").trigger('change');
});

trigger simulates the change event on loading the page

触发器模拟加载页面时的更改事件

#1


2  

you can call it on page load:

你可以在页面加载时调用它:

$(document).ready(function(){
  $("select").trigger('change');
});

trigger simulates the change event on loading the page

触发器模拟加载页面时的更改事件