繁体   English   中英

jQuery:与textarea元素相互转换

[英]JQuery: Convert to & from textarea element

我是JQuery的新手,我正在尝试做一些不确定的事情,我不确定我可以在JQuery中做些什么。

  • 我可以使用JQuery(甚至本地Javascript)函数获取HTML元素类型吗? 如果是这样,函数的名称是什么?
  • 我想更新/设置HTML元素类属性。 您会建议我只使用普通的旧setAttribute()还是应该使用JQuery函数? 如果我应该使用JQuery函数,函数的名称是什么?
  • 是否有返回HTML元素类的JavaScript函数? 是this.getAttribute(“ class”);吗?

经验更丰富的JQuery程序员:您将如何改进试图将元素更改为textarea然后再返回的JQuery HTML代码(目前缺少某些功能):

<html>
<head>

    <script type="text/javascript" src="jquery-1.6.4.js"></script>
    <script type="text/javascript">
    <!--
        var STATE = 0;

        function Toggle()
        {
            if (STATE==1) { convertToUpdatable(); STATE = 0; }
            else          { convertToStatic();    STATE = 1; }
        }

        function convertToUpdatable()
        {
            // Post: Convert all HTML elements (with the class 'updatable') to textarea HTML elements
            //       and store their HTML element type in the class attribute
            // EG: Before: <p class="updatable"/> Hello this is some text 1 </p>
            //     After : <textarea class="updatable p"/> Hello this is some text 1 </textarea>

            $(".updatable").each(function()
                {
                    $(this).replaceWith("<textarea>"+$(this).text() +"</textarea>");
                    // TODO store this elements type in class attribute
                    // The below is guessing that there are jquery functions getType()
                    $(this).setAttribute( "class", $(this).getAttribute("class") + $(this).getType() );
                });
        }

        function convertToStatic()
        {
            // Post: Find all HTML elements (with the class 'updatable'), check to see if they are part of another class aswell
            //       (which will be their original HTML element type) & convert the element back to that original HTML element type

            $(".updatable").each(function()
                {
                    // This uses javascript functions: how can I write this in JQuery
                    var type = this.getAttribute("class").replace("updatable","").replace(" ", "");

                    if (type == "") { alert("Updatable element had no type defined in class attribute"); return; }

                    $(this).replaceWith( type +$(this).text() + type );
                    $(this).setAttribute( "class", "updatable" );
                });
        }

    -->
    </script>
</head>
<body>

    <p class="updatable"/> Hello this is some text 1 </p>
    <b class="updatable"/> Hello this is some text 2 </b>
    <i class="updatable"/> Hello this is some text 3 </i>

    <input id="MyButton" type="button" value="Click me!" onclick="Toggle();" />

</body>
</html>

Javascript:

your_element.className = 'some_class';
your_element.nodeName;

暂无
暂无

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

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