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

时间:2014-06-17 16:33:53

标签: javascript jquery

如何将此代码的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版本是什么?

2 个答案:

答案 0 :(得分:1)

这可以用作非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/

答案 1 :(得分:0)

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

最后,您在节点上触发change事件,根据您要支持的浏览器,这在vanilla中要复杂一点,但您可以使用{{1与element.dispatchEvent

所以一起,

new Event(type)