将div元素替换为链接

问题描述 投票:1回答:1
function replaceLink(href_array){
    $('.externalLink').each(function(index){
        $(this).replaceWith(function() {
            if ($(this).text() != "") {
                return $('<a />').append($(this).contents()).attr('href', href_array[index]);
            }
            else { // do not use
                return $('<a />').append(href_array[index]).attr('href', href_array[index]);
            }
        });
    });
};

初始页面具有以下结构

body 
    p div.externalLink /p
    p div.externalLink /p
    p div.externalLink /p
    p div.externalLink /p
    p div.externalLink /p
    p div.externalLink /p
/body

脚本应该是

body 
    p a#href /p
    p a#href /p
    p a#href /p
    p a#href /p
    p a#href /p
    p a#href /p
/body

但事实证明

body 
    p /p a#href
    p /p a#href 
    p /p a#href
    p /p a#href
    p /p a#href
    p /p a#href
/body

怎么样?

at the bottom as it should be on top of how it turns out

javascript jquery
1个回答
2
投票

你正在div标签内创建p标签,这是不正确的,开放的div标签将自动关闭之前的p标签,因此replaceWith工作不正确。

div内尝试div

来源 - Why <p> tag can't contain <div> tag inside it?

var href_array = [
  "Href1", "Href2", "Href3", "Href4", "Href5", "Href6"
]
function replaceLink(href_array){
    $('.externalLink').each(function(index){
        $(this).replaceWith(function() {
            if ($(this).text() != "") {
                return $('<a />').append($(this).contents()).attr('href', href_array[index]);
            }
            else { // do not use
                return $('<a />').append(href_array[index]).attr('href', href_array[index]);
            }
        });
    });
}

replaceLink(href_array)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>

<body>
  <div>
    <div class="externalLink">A</div>
  </div>
  <div>
    <div class="externalLink">B</div>
  </div>
  <div>
    <div class="externalLink">C</div>
  </div>
  <div>
    <div class="externalLink">D</div>
  </div>
  <div>
    <div class="externalLink">E</div>
  </div>
  <div>
    <div class="externalLink">F</div>
</body>

</html>
© www.soinside.com 2019 - 2024. All rights reserved.