.change()和.toggle()的非JQuery版本是什么?

What are the non JQuery versions of .change() and .toggle()?

本文关键字:版本 是什么 JQuery toggle change 的非      更新时间:2023-09-26

如何将此代码的JQuery版本转换为非JQuery?

JQuery

jQuery(function($){
    //change event handler for the checkbox
    $('#isTracefile').change(function(){
        //if it is checked set the select element's container to display else hide
        $('#cttracefile').toggle(this.checked);
        //if it is unchecked set the input element's container to display else hide
        $('#custom').toggle(!this.checked);
    }).change()
})

        <div id="cttracefile">
            Sample Tracefiles to use: 
            <select name="tracefile">
                <option value="capacity.13Mbps_200RTT_PER_0.000001.txt">capacity.13Mbps_200RTT_PER_0.000001</option>
            </select> 
        </div>
        <div id="custom">
            <label>Forward Delay: </label><input id="fd" type="number" min="0" max="1000" step="1" value ="100"/> ms
            <br/>
            <label>Reverse Delay: </label><input id="rd" type="number" min="0" max="1000" step="1" value ="100"/> ms
            <br/>
            <label>Download Capacity: </label><input id="down" type="number" min="1" max="30" step="1" value ="1"/> MBps
            <br/>
            <label>Upload Capacity: </label><input id="up" type="number" min="1" max="30" step="1" value ="1"/> MBps
            <br/>
            <label>Packet Error Rate (PER): </label><input id="per" type="number" min="0.00001" max="1" step="0.00001" value ="0.00001"/>
        </div>

.change().toggle()的非jquery版本是什么

这可以用作非jquery的解决方案。你只需要设置初始值

var isTrace = document.getElementById('isTracefile');
var ctTrace = document.getElementById('cttracefile');
var custom = document.getElementById('custom');
isTrace.onchange = function(){
    if (isTrace.checked) {
        ctTrace.style.display = "none";
        custom.style.display = "block";
    } else {
        custom.style.display = "none";
        ctTrace.style.display = "block";
    }
};

演示小提琴:http://jsfiddle.net/adjit/3at2c/4/

  • $(fn)变为window.addEventListener('load', fn)
  • $('#id')变为document.getElementById('id')
  • $jqo.change(fn)变为element.addEventListener('change', fn)
  • 基于bool element.style.display = bool ? '' : 'none'更改可见性

最后,在节点上触发change事件,这在vanilla中要做得更复杂一些,具体取决于您想要支持的浏览器,但是您可以使用element.dispatchEventnew Event(type)

所以全部加起来,

window.addEventListener('load', function () {
    document.getElementById('isTracefile')
        .addEventListener('change', function () {
            document.getElementById('cttracefile')
                .style.display = this.checked ? '' : 'none';
            document.getElementById('custom')
                .style.display = !this.checked ? '' : 'none';
        });
    document.getElementById('isTracefile').dispatchEvent(new Event('change'));
});