JavaScript fire事件选择某些选项

时间:2018-02-14 07:42:21

标签: javascript events

JavaScript fire事件选择了一些选项。 示例:我有4个选项(1.选项A,2。选项B,3.Option C,4.Option D,选项E),如果我选择选项(2或3),则应触发事件。但是,在选择其他选项时不应该发生任何事情。

HTML:

var selectElem = document.getElementById('select')
var pElem = document.getElementById('p')

// When a new <option> is selected
selectElem.addEventListener('change', function() {
  var index = selectElem.selectedIndex;
  // Add that data to the <p>
  pElem.innerHTML = 'selectedIndex: ' + index;
})
<p id="p">selectedIndex: 0</p>

<select id="select">
  <option selected>Option A</option>
  <option>Option B</option>
  <option>Option C</option>
  <option>Option D</option>
  <option>Option E</option>
</select>

1 个答案:

答案 0 :(得分:0)

您提到事件应该触发。 如果您将事件视为简单的功能,则以下代码可以正常运行。

如果您真的打算触发自定义事件,那么只需在if check

中使用这两行
// Create the event
var event = new CustomEvent("name-of-event", { "detail": "Example of an event" });

// Dispatch/Trigger/Fire the event
document.dispatchEvent(event);

完整的代码:

<html>
    <body>

        <p id="idIndex">selectedIndex: 0</p>

        <select id="idSelect">
            <option selected>Option A</option>
            <option>Option B</option>
            <option>Option C</option>
            <option>Option D</option>
            <option>Option E</option>
        </select>
        </br>

        <script>
            var selectElem  = document.getElementById('idSelect')
            var indexElem   = document.getElementById('idIndex')

            // When a new <option> is selected
            selectElem.addEventListener('change', function() {

                // Get selected index
                var index = selectElem.selectedIndex;

                // Add selected index to the <p>
                indexElem.innerHTML = 'selectedIndex: ' + index;

                // If index selected is your desired index
                if ( index === 2 || index == 3 ) {
                    // Call your desired function here or trigger event
                    console.log("Call the function needed");
                }
            });
        </script>
    </body>
</html>