如何替换元素标记,然后将其添加到现有元素?

时间:2015-12-02 19:05:24

标签: javascript jquery html

我有一个 context.startActivity(new Intent(context,YourNewActivity.class)); 标记后跟一个<img>标记,我将其保存在名为<span>的变量中。但是,在使用$contents<span>标记添加到图片代码之前,我想将<figcaption>标记替换为add()。我似乎无法做到这一点。这是我到目前为止所做的:

首先是HTML

<img src="whatever.jpg" />
<span>Copyright Stackoverflow</span>

使用此Jquery代码:

  $elem.find("img, img + span").each(function(innerIndex) {
    var $contents = $(this).add($(this).next('span'));
    });

我最终得到的结果:

  

<img src="whatever.jpg" /> <span>Copyright Stackoverflow</span>

我想要发生的事情更像是这样(如果它不起作用的话):

$elem.find("img, img + span").each(function(innerIndex) {

// first replace the span with a figcaption
var $figcaption = $(this).next('span').unwrap().wrap('<figcaption/>');

// add the new element to the img tag to make the new contents
var $contents = $(this).add($figcaption);
});

所以我最终可以这样做:

  

<img src="whatever.jpg" /> <figcaption>Copyright Stackoverflow</figcaption>

当我将$contents输出到页面时,我会得到一个空的<span>,而不是<figcaption>个标记中包含的<img src="whatever.jpg" /><figcaption>Copyright</figcaption>。我该怎么做?

更新:为了澄清,我需要将完成的HTML转换为变量,因为它稍后会在不同的地方使用。所有这些{{1}}必须在var。

4 个答案:

答案 0 :(得分:3)

要转:

<img src="whatever.jpg" />
<span>Copyright Stackoverflow</span>

分为:

<img src="whatever.jpg" />
<figcaption>Copyright Stackoverflow</figcaption>

我建议:

// selecting the relevant elements,
// using the replaceWith() method to
// replace those found elements:
$('img + span').replaceWith(function(){

  // returning a string comprised of the HTML tags,
  // surrounding the text from the 'this' (the current
  // <span> element of the jQuery collection) node:
  return '<figcaption>' + this.textContent + '</figcaption>'
});

$('img + span').replaceWith(function(i, el) {
  return '<figcaption>' + this.textContent + '</figcaption>'
});
span {
  color: limegreen;
}
figcaption {
  color: #f90;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src="whatever.jpg" />
<span>Copyright Stackoverflow</span>

JS Fiddle demo

或者,为了在任何子元素上保留事件处理程序:

// a simple function bound to the click event
// on the <span> element within a parent <span>
// element:
$('span > span').click(function () {
  console.log('woo');
})

// finding the relevant <span> elements:
$('img + span').replaceWith(function () {

  // returning a created <figcaption> element,
  // after appending the contents of the
  // found <span> element(s):
  return $('<figcaption>').append($(this).contents());
});

$('span > span').click(function() {
  console.log('woo');
})

$('img + span').replaceWith(function() {
  return $('<figcaption>').append($(this).contents());
});
span {
  color: limegreen;
}
figcaption {
  color: #f90;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src="whatever.jpg" />
<span><span>Copyright</span> Stackoverflow</span>

JS Fiddle demo

或者,在原生JavaScript中:

// creating a named function, and its arguments:
function replaceWith(original, tag) {

  // tag: String, the element-type to be created,
  // here we remove any '<' or '>' characters, to
  // ensure that '<fieldset>' becomes 'fieldset':
  tag = tag.replace(/<|>/g, '');

  // creating a new element of that type:
  var newEl = document.createElement(tag);

  // setting the innerHTML of the created element
  // that of the original element:
  newEl.innerHTML = original.innerHTML;

  // replacing the original child with the new element:
  original.parentNode.replaceChild(newEl, original);
}

// finding the relevant elements:
var elements = document.querySelectorAll('img + span'),

  // converting the collection of elements into an
  // an Array:
  elementArray = Array.prototype.slice.call(elements, 0);

// iterating over the Array using Array.prototype.forEach():
elementArray.forEach(function (elem) {

  // calling the function, passing in the current array-element
  // of the array over which we're iterating:
  replaceWith(elem, '<figcaption>')
});

function replaceWith(original, tag) {
  tag = tag.replace(/<|>/g, '');
  var newEl = document.createElement(tag);
  newEl.innerHTML = original.innerHTML;

  original.parentNode.replaceChild(newEl, original);
}

var elements = document.querySelectorAll('img + span'),
  elementArray = Array.prototype.slice.call(elements, 0);

elementArray.forEach(function(elem) {
  replaceWith(elem, '<figcaption>')
});
span {
  color: limegreen;
}
figcaption {
  color: #f90;
}
<img src="whatever.jpg" />
<span>Copyright Stackoverflow</span>

JS Fiddle demo

此外,如果您希望在子元素上保留事件处理程序 - 使用本机JavaScript:

// finding the <span> elements with a <span> parent:
document
  .querySelector('span > span')

  // adding a simple anonymous function as the
  // handler for the click event:
  .addEventListener('click', function () {

    // logging a simple message to the console:
    console.log('woo')
  });

function replaceWith(original, tag) {
  tag = tag.replace(/<|>/g, '');
  var newEl = document.createElement(tag);

  // this is the only change, while the
  // original element contains a firstChild node
  // we append that child-node to the newly
  // created-element:
  while (original.firstChild) {

    // using Node.appendChild to move the firstChild
    // of the original node into the created-element:
    newEl.appendChild(original.firstChild)
  }

  original.parentNode.replaceChild(newEl, original);
}

var elements = document.querySelectorAll('img + span'),
  elementArray = Array.prototype.slice.call(elements, 0);

elementArray.forEach(function (elem) {
  replaceWith(elem, '<figcaption>')
});

document.querySelector('span > span').addEventListener('click', function() {
  console.log('woo')
});

function replaceWith(original, tag) {
  tag = tag.replace(/<|>/g, '');
  var newEl = document.createElement(tag);
  while (original.firstChild) {
    newEl.appendChild(original.firstChild)
  }

  original.parentNode.replaceChild(newEl, original);
}

var elements = document.querySelectorAll('img + span'),
  elementArray = Array.prototype.slice.call(elements, 0);

elementArray.forEach(function(elem) {
  replaceWith(elem, '<figcaption>')
});
span {
  color: limegreen;
}
figcaption {
  color: #f90;
}
<img src="whatever.jpg" />
<span><span>Copyright</span> Stackoverflow</span>

JS Fiddle demo

参考文献:

答案 1 :(得分:2)

$(function() {
  //create figcaption empty
  var figcaption = $('<figcaption/>');

  //get span
  var span = $('span:first');

  //replacement behind the scenes
  figcaption.html(span.html());

  //replace in dom
  span.replaceWith(figcaption);

  //verify
  alert($('body').html());
});

https://jsfiddle.net/rodrigo/Lfvotuze/

答案 2 :(得分:1)

尝试类似的东西:

$elem.find("img").each(function(innerIndex) {
    var span = $(this).next('span');//gets the next span from the img
    var $contents = span.text();//gets the content
    span.remove();//removes the span
    //adds the figcaption after the img tag
    $(this).after('<figcaption>'+$contents+'</figcaption>');
});

jsfiddle:https://jsfiddle.net/t5dLcw12/

答案 3 :(得分:0)

这非常简单。用我们的新标签包裹span内部,然后通过展开新标签删除span,然后创建两者的克隆(myclone现在保存你的&#34; new&#34;元素):

$('span').wrapInner('<figcaption/>').find('figcaption').unwrap();
var myclone = $('img').add('figcaption').clone();

同一条链:

var myclonea = $('span').wrapInner('<figcaption/>').find('figcaption').unwrap().add('img').clone();

注意关于原始包装上可能需要移动到新包装器的事件处理程序,您可以根据需要引用此帖子:jQuery find events handlers registered with an object

相关问题