It is bad to put <span /> tags inside <option /> tags, only for string manipulation not styling?

旧时模样 提交于 2019-11-26 13:49:31

From the HTML 4.01 spec:

<!ELEMENT OPTION - O (#PCDATA)         -- selectable choice -->

From the HTML 5 draft spec:

Content model: Text.

(Even the HTML 3.2 and HTML 2 specs say: <!ELEMENT OPTION - O (#PCDATA)*>)

An option element cannot have any child elements. So yes, it is bad.

You can use a Javascript plugin to overcome this limitation. For example jQuery plugin "Select2" Select2 plugin homepage. I use it in a couple of my projects and think that it's pretty flexible and convenient.

There are a number of them, but they do quite same thing - convert traditional <select> into <div> blocks with an extra functionality.

The option element

Content model: Text

No, it’s not ok. Consider keeping the values around in your script so you can recompose them when necessary.

You're better off using an HTML replacement for your <select> if you want to do this.

As established by other people, and I have tried with <b> and other tags, <option> does not take tags within it.

What you can do, since you cannot use <span> inside an <option> tag,
You can use the index number to extract the text via
document.getElementById(selectid).options[x].text where x is the relevant index, as a variable.

Then what you do is use the " (" to split the variable into the time, and remove the last character as well which removes the ")"

Sample:

    <script type="text/javascript">
    function extractSelectText()
    {
    var text = document.getElementById("main").options[1].text
    /* 
    var tlength = text.length
    var splitno = tlength - 1
    var text2 = text.slice(0, splitno)
    var textArray = text2.split(" )")
    var time = textArray[0]
    var hours = textArray[1]
    }
    </script>

Changing it is much simpler:

    <script type="text/javascript">
    function changeSelectText()
    {
    /* add your code here to determine the value for the time (use variable time) */

    /* add your code here to determine the value for the hour (use variable hours) */
   var textvalue = time + " (" + hours + ")"
   document.getElementById("main").options[1].text
   }
   </script>

If you use a for function you can change each value of the select replacing 1 with 2, 3 and so on, and put a set interval function to constantly update it.

One option for editing would be to use some fancy pattern matching to update the content. It will be slower and more resource intensive, and depends on how regular the format is, but doesn't require any HTML modifications. My concern, however, would be on accessibility and the user experience. Having values change is hard for screen reader software to pick up, and it may also confuse other users.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!