【问题标题】:Dynamically change element's TagName动态改变元素的 TagName
【发布时间】:2021-07-26 01:00:35
【问题描述】:

根据jQuery API's Documentation,我正在使用正确的事件处理程序。

我也知道所陈述的 IE 问题,我不在乎,因为这只是一个有趣的实验。

注意: 试图更改通过 HTML 创建或已在 HTML 文档中的 input 元素的 type 属性(或属性) 将导致 Internet Explorer 6、7 或 8 引发错误。

所以我一直在努力让它发挥作用,但我有几个问题:

  1. 这可能吗?
  2. 如果是这样,我做错了什么?如何解决?

编辑

我的意图是将.selected 的标签从span 更改为用户指定的任何内容。我最初以button 为例,但我看到我的帖子很容易被误解。因为我的意图是将span 标记更改为从buttoninput[type=text] 元素的任何内容。一切都取决于用户在文本框中键入的内容。

我不知道replaceWidth 在这种情况下会如何帮助我。我怎样才能对此有更多了解?

$(document).ready(function() {
  // Show active tag
  $(".activetag").html( $(".selected").prop("tagName").toLowerCase() );

  // Change selected element's tag
  $(".convert").on("keyup", function() {
    $(".selected").replaceWidth( $("div") ).html( $(".selected").html() );
  });

  // Show selected element's code
  // ex. <span class="selected">Hello world</span>
  $(".code").val( $(".selected").html() );
});
<!DOCTYPE html>
<html>
  <head>
    <title>new document</title>
    <meta charset='utf-8'>
    <meta name='viewport' content='initial-scale=1.0'>
    <meta http-equiv='X-UA-Compatible' content='IE=9' />
    <link type='text/css' rel='stylesheet' href='http://necolas.github.io/normalize.css/3.0.1/normalize.css'/>
    <script type='text/javascript' src='http://code.jquery.com/jquery-latest.min.js'></script>
  </head>
  <body>
    <div align="center">
      <span class="activetag">Hello world</span><br />
      <input type="text" class="convert"><br />
      <span class="selected">Hello world</span><br />
      <textarea class="code"></textarea>
    </div>
  </body>
</html>

【问题讨论】:

  • 是什么让您认为您可以更改.tagName?通常的解决方案是用您想要的类型的新 DOM 元素替换当前标签(及其子标签)。
  • 这不是一个骗子 imo,因为它似乎将输入类型属性与标记名混淆了,可能需要$(".selected").attr("type", "button");
  • @andrew - 因此,由 OP 来澄清他们的问题,而不是我们猜测他们“可能”的实际含义。
  • tagName 属性是只读的,不能更改。正如 jfriend00 所建议的那样,您可以将一个元素替换为另一个元素,并将属性和属性从一个元素复制到另一个元素。但并非所有属性在元素之间都是通用的,例如复选框具有选中属性,文本输入没有。

标签: javascript jquery


【解决方案1】:

JS 更改标签名称

/**
 * This function replaces the DOM elements's tag name with you desire
 * Example:
 *        replaceElem('header','ram');
 *        replaceElem('div.header-one','ram');
 */
function replaceElem(targetId, replaceWith){
  $(targetId).each(function(){
    var attributes = concatHashToString(this.attributes);
    var replacingStartTag = '<' + replaceWith + attributes +'>';
    var replacingEndTag = '</' + replaceWith + '>';
    $(this).replaceWith(replacingStartTag + $(this).html() + replacingEndTag);
  });
}
replaceElem('div','span');

/**
 * This function concats the attributes of old elements
 */
function concatHashToString(hash){
  var emptyStr = '';
  $.each(hash, function(index){
    emptyStr += ' ' + hash[index].name + '="' + hash[index].value + '"';
  });
  return emptyStr;
}

相关的小提琴在这个link

【讨论】:

【解决方案2】:

这是一个可以完成工作的小曲:

var el = document.querySelector('.js-the-thing');
var outer = el.outerHTML;
el.parentElement.innerHTML = outer.replace(/(<)(\/)?strong\b/gi, '$1$2em');

示例:将strong 替换为em

var outer = "<strong><stronger><strong yes></strong></stronger></strong>";
outer.replace(/(<)(\/)?strong\b/gi, '$1$2em');

"<em><stronger><em yes></em></stronger></em>"

请记住,您会丢失任何附加到元素的事件处理程序,但如果您使用在组件级别附加侦听器的标准做法,或 onclick= 的野蛮做法,您将美好的。 ?

如果您不想替换所有类似标记的元素,您也可以使用.innerHTML 保存它们,然后替换新元素的.innerHTML

【讨论】:

    【解决方案3】:

    所以在了解到您不能直接更改 tagName 之后。仍然有几种方法可以做到这一点。

    下面的示例是使用隐藏的文本区域来保存 html,并使用文本框、按钮和 .replaceWith 更改我们的标签。这样我们就有了更多的控制权,而不仅仅是使用 keyup。同样,这样我就不必担心丢失我的元素,而且我还节省了处理能力,因为我没有让浏览器做超出它需要做的工作。

    Here's 一个使用名为.replaceTagName 的JQuery 插件的小提琴。 (这个插件不适合我的需要。因为我也想打电话给input[type=text],这个插件不允许这样的事情,因为它处理 html 而不是值。但是这个插件可能仍然对其他人有帮助)

    Here's 下面是相同内容的演示,但我使用的是条件/三元运算符。

    $(document).ready(function() {
    
      // Change selected element's tag function
      var changeTagName = function() {
        var $val = $(".newtag").val().trim().toLowerCase();
    
        // If no value is set return to default
        if ($.inArray($val, [""]) > -1) {
          $(".selected").replaceWith( "<span class=\"selected\" \>");
          $(".selected").html( $(".code").val() );
          // Check if it's a textbox
        } else if ($.inArray($val, ["input[type=text]", "input", "textbox"]) > -1) {
          $(".selected").replaceWith( "<input type=\"text\" class=\"selected\" \>");
          $(".selected").val( $(".code").val() );
    
          // Check if it's an input button
        } else if ( $val === "input[type=button]" ) {
          $(".selected").replaceWith( "<input type=\"button\" class=\"selected\" \>");
          $(".selected").val( $(".code").val() );
    
          // Check if it's a textarea
        } else if ( $val === "textarea" ) {
          $(".selected").replaceWith( "<" + $val + " class=\"selected\" \>");
          $(".selected").val( $(".code").val() );
    
          // Use text as a placeholder to make a span tag
        } else if ( $val === "text" ) {
          $(".selected").replaceWith( "<span class=\"selected\" \>");
          $(".selected").html( $(".code").val() );
        } else {
    
          // Make any others specified
          $(".selected").replaceWith( "<" + $val + " class=\"selected\" \>");
          $(".selected").html( $(".code").val() );
        }
    
        // Return tagName
        $(".newtag").val( $(".selected").prop("tagName").toLowerCase() );
      };
    
      // Change tagName from "Enter" Key
      $(document).keydown(function(e) {
        if ($(".newtag").is(":focus")) {
          if (e.which === 13) {
            changeTagName();
          }
        }
      });
    
      // Change selected element's tag
      $(".convert").on("click", function() {
        changeTagName();
      });
    
      // Show selected element's code
      // ex. <span class="selected">Hello world</span>
      $(".code").val( $(".selected").html() );
    });
    .hide {
      display: none;
    }
    <!DOCTYPE html>
    <html>
      <head>
        <title>new document</title>
        <meta charset='utf-8'>
        <meta name='viewport' content='initial-scale=1.0'>
        <meta http-equiv='X-UA-Compatible' content='IE=9' />
        <link type='text/css' rel='stylesheet' href='http://necolas.github.io/normalize.css/3.0.1/normalize.css'/>
        <script type='text/javascript' src='http://code.jquery.com/jquery-latest.min.js'></script>
      </head>
      <body>
        <div align="center">
          <input type="text" class="newtag" placeholder="tagName here..."><br />
          <input type="button" class="convert" value="convert"><br />
          <span class="selected">Hello world</span><br />
          <textarea class="code hide"></textarea>
        </div>
      </body>
    </html>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-06-19
      • 2012-03-30
      • 2018-07-10
      • 1970-01-01
      • 2021-10-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多