简体   繁体   English

使用 Javascript 和字符串插值更改 html 元素的类

[英]Changing class of html element using Javascript and string interpolation

I have a HTML element with the id of "bigOne".我有一个 ID 为“bigOne”的 HTML 元素。 Its size is determined by its class and the associated CSS.它的大小由它的类和相关联的 CSS 决定。 The class names are "p1", "p2", "p3", etc, all the way up to "p100".类名是“p1”、“p2”、“p3”等,一直到“p100”。

One the page is an input and a button.一个页面是一个输入和一个按钮。 I am trying to create a function so that when a number is typed in the input and the button clicked that the class of the "bigOne" is changed to the corresponding number, eg when 80 is entered and the button clicked the class changed from "p50" to "p80".我正在尝试创建一个函数,以便当在输入中键入一个数字并单击按钮时,“bigOne”的类将更改为相应的数字,例如,当输入 80 并且单击按钮时,类从“ p50”到“p80”。 In my code below I have been able to create this exact scenario but what I want to be able to do is be able to type in any number and change the class appropriately, eg submitting 4 creates the class p4 or submitting 99 creates the class p99.在我下面的代码中,我已经能够创建这个确切的场景,但我想要做的是能够输入任何数字并适当地更改类,例如提交 4 创建类 p4 或提交 99 创建类 p99 . This is where I have come completely stuck.这就是我完全陷入困境的地方。

Im am sure there isn't too much code required but I just can not get it.我确信不需要太多代码,但我就是无法得到它。

<div id="options">
                <label></label>
                <input id="changes" />
                <button id="myButton">Submit</button>
            </div>

            <script type="text/javascript">

                document.getElementById("myButton").onclick=function() {

                    if (document.getElementById("changes").value=="80") {  


                        document.getElementById("bigOne").classList.contains('p50');

                        document.getElementById("bigOne").classList.toggle('p80');

                    }


                }







            </script>

Since you tag your question with jquery... :由于您使用 jquery... 标记您的问题:

<script>

   $(function(){
       $('#myButton').click(function(){
           $('#bigOne').removeClass(); //to clean old classes
           //we get the value from the input and add the p class
           $('#bigOne').addClass('p'+$('#changes').val());
       });
    });
</script>

I suggest that you fetch the value of the element where the number is put in, and store it into the string below called "theNewClassName":我建议您获取输入数字的元素的值,并将其存储到下面名为“theNewClassName”的字符串中:

var theNewClassName = document.getElementById("elementToTakeValueFrom").innerHTML;
document.getElementById("elementToGiveClassTo").className = theNewClassName; 
//or whatever classname you wanted it to change to

Or或者

document.getElementById("bigOne").className = "blablabla";

You get the idea.你明白了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM