jQuery将标题标记从一个div附加到另一个div

时间:2017-08-23 16:22:28

标签: jquery

我试图从名为.swatch.selected的div中获取title属性并将其移动到我创建的名为.variationTitle的新div中。我不得不通过jQuery追加添加.variationTitle。 这是HTML代码:

<div class="tawcvs-swatches" data-attribute_name="attribute_pa_foundation-shades">
  <span class="swatch swatch-image swatch-vanilla " title="Vanilla" data-value="vanilla">
    <img src="image tag here" alt="Vanilla">
  </span>
<div class="variationTitle"></div>
</div>

jQuery的:

$( ".tawcvs-swatches" ).append( "<div class='variationTitle'></div>" );

单击跨度图像时,会自动将一个选定的类添加到span标记中。

3 个答案:

答案 0 :(得分:1)

title属性获取标题。在图像上放置一个监听器,以便在单击时放入文本。

var title = $('.swatch-vanilla').attr('title');

$('img').on('click', function() {
  $('.variationTitle').text(title);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="tawcvs-swatches" data-attribute_name="attribute_pa_foundation-shades">
  <span class="swatch swatch-image swatch-vanilla " title="Vanilla" data-value="vanilla">
    <img src="http://via.placeholder.com/350x150?text=Vanilla" alt="Vanilla">
  </span>
<div class="variationTitle"></div>
</div>

以上内容适用于特定示例,但您可以使其更加健壮:

$('.swatch').on('click', function() {
  var title = $(this).attr('title');
  $(this).siblings('.variationTitle').text(title);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="tawcvs-swatches" data-attribute_name="attribute_pa_foundation-shades">
  <span class="swatch swatch-image swatch-vanilla " title="Vanilla" data-value="vanilla">
    <img src="http://via.placeholder.com/350x150?text=Vanilla" alt="Vanilla">
  </span>
<div class="variationTitle"></div>
</div>
<div class="tawcvs-swatches" data-attribute_name="attribute_pa_foundation-shades">
  <span class="swatch swatch-image swatch-chocolate " title="Chocolate" data-value="vanilla">
    <img src="http://via.placeholder.com/350x150?text=Chocolate" alt="Chocolate">
  </span>
<div class="variationTitle"></div>
</div>
<div class="tawcvs-swatches" data-attribute_name="attribute_pa_foundation-shades">
  <span class="swatch swatch-image swatch-peach " title="Peach" data-value="vanilla">
    <img src="http://via.placeholder.com/350x150?text=Peach" alt="Peach">
  </span>
<div class="variationTitle"></div>
</div>

答案 1 :(得分:1)

我认为这应该有效:

http://jsfiddle.net/hHLXr/364/

$('.swatch').click(function() {
    var text = $(".swatch").attr("title");
    $('.variationTitle').text(text);
});

您基本上获取属性的值,并将下一个元素的文本设置为该值。希望它有所帮助:)

答案 2 :(得分:0)

这是你如何做到的,

我在{{3}}

上做了快速草稿
reader.NodeType == XmlNodeType.Element && reader.LocalName == XmlElementName