使用 If/else 语句根据滑块值进行赋值

我正在尝试使用滑块更改值的显示方式。我制作了一个标签,显示如下值。


课程时长:1天


此处显示的值根据滑块值而变化。


因此,当滑块值为 1 时,应显示为“天”,当滑块值大于 1 时,应显示为“天”。


我在我的 javascript 中使用 if/else 语句来更改根据滑块值显示的名称。我使用的编码如下。


JS文件:


// method used to get value from slider and display. 


function slider_value() {


    var slider = document.getElementById("myRange");

    var output = document.getElementById("demo");


    output.innerHTML = slider.value;


    slider.oninput = function () {

        output.innerHTML = this.value;

    }

}


// method used to change name according to slider value


function value_name() {


    var count = document.getElementById("myRange");

    var outname = document.getElementById("dname"); 


    if (parseInt(count.value) == 1) {

        outname.innerHTML = "Day";

    }

    else {

        outname.innerHTML = "Days";

    }

}

HTML文件:


<label for="duration">


    Course Duration :


    <span id="demo"></span>

    <span id="dname"></span>


</label>


<div class="slidecontainer">


    <input type="range" min="1" max="15" value="1" class="slider" id="myRange">


</div>

我已将函数调用到视图中,如下所示:


<script> 

    slider_value();

    value_name();

</script>

编码在调试时不会显示任何错误,但它只会显示一天或几天,不会根据滑块值进行更改。所以我期待一些帮助和想法来纠正这个问题。


交互式爱情
浏览 192回答 3
3回答

繁花如伊

不需要复杂的 js 计算,你可以很容易地用change事件来做到这一点。将事件侦听器添加到input,然后在那里添加逻辑,检查代码段var el = document.getElementById('myRange');el.addEventListener('change', function(event){&nbsp; var value = event.target.value;&nbsp; var _container = document.getElementById('demo');&nbsp; value == 1 ? _container.innerText = value+' Day' : _container.innerText = value+' Days'})<label for="duration">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Course Duration :&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span id="demo"></span>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span id="dname"></span>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </label>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <div class="slidecontainer">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <input type="range" min="1" max="15" value="1" class="slider" id="myRange">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </div>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript