简体   繁体   English

将 div 元素替换为链接

[英]To replace a div element to the link

I'm using below code for replacing links:我正在使用以下代码替换链接:

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]);
            }
        });
    });
};

The initial page has the following structure:初始页面具有以下结构:

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

After the script, it should be:在脚本之后,它应该是:

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

But it turns out like this:但结果是这样的:

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

How can I correct this?我该如何纠正?

at the bottom as it should be on top of how it turns out在底部,因为它应该在结果之上

You are creating div tags inside p tags, which is incorrect and the opening div tag will automatically close the p tag before it, hence the replaceWith works incorrectly.您正在p标签内创建div标签,这是不正确的,打开的div标签将自动关闭它之前的p标签,因此replaceWith工作不正确。

Try a div inside div .试试div里面的div

Source - Why can't the <p> tag contain a <div> tag inside it? Source - 为什么 <p> 标签里面不能包含 <div> 标签?

 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> <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> </div>

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

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