从属性中获取数据并使用它来替换其他文本

Get data from attribute and use it to replace other text

本文关键字:替换 其他 文本 获取 数据 从属性      更新时间:2023-09-26

我正在构建一个图例-当用户单击一个图标时,我想从"data-title"属性中抓取数据,然后使用该文本来替换"p.map-legend-key__copy",该文本目前表示"Marker text"。

这是目前为止我的代码…

HTML:

<div class="map-legend">
    <ul class="map-legend-list cf">
        <li class="map-legend-list__item legend-1" data-title="legend one"><i class="fa fa-map-marker"></i></li>
        <li class="map-legend-list__item legend-2" data-title="legend two"><i class="fa fa-map-marker"></i></li>
        <li class="map-legend-list__item legend-3" data-title="legend three"><i class="fa fa-map-marker"></i></li>
        <li class="map-legend-list__item legend-4" data-title="legend four"><i class="fa fa-map-marker"></i></li>
        <li class="map-legend-list__item legend-5" data-title="legend five"><i class="fa fa-map-marker"></i></li>
    </ul>
    <div class="map-legend-key">
        <p class="map-legend-key__copy">Marker text</p>
    </div>
</div><!-- map-legend -->
jQuery:

$('.map-legend-list__item').click(function() {
    var legendText = $(this).attr('data-title');
    $('p.map-legend-key__copy').replace('Marker text', legendText);
});

Thnaks,杰克。

应该有

var legendText = $(this).data('title');

如果你想替换整个文本

$('p.map-legend-key__copy').text(legendText);

如果您只想替换Marker text

$('p.map-legend-key__copy').text($('p.map-legend-key__copy').text().replace('Marker text', legendText));

这可以是另一种方式:

var legendText = $(this).data('title');
$(".p.map-legend-key__copy").html(function(i,t){
    return t.replace('Marker text', legendText)
});