用第二个参数替换()作为变量?

时间:2017-03-12 23:26:10

标签: javascript jquery html css

我的功能是用图像替换div,并在一段时间后将其重置回同一个div。当替换div时,我需要添加自定义HTML数据属性,但是使用replaceWith()方法我必须先设置div然后再替换它。在这个例子中,我需要更新'data-x'和'data-y'属性,这些属性将存储为数组x_cord和y_cord中的第一项。函数的第一部分按预期工作,问题发生在setTimeout部分。

我试图使用占位符替换名为changex和changey的值。我不能让revert.replace(“changex”,x_cord [0])按预期工作,或者我不能做到这一点?我已经查看了我的问题并看过正则表达式解决方案,但这只适用于人们正在寻找的字符串,而不是人们想要将其更改为的字符串。

tl; dr:我需要将'changex'和'changey'更改为x_cord [0]和y_cord [0]。

function explode(e){
var obj = $(e);
var replacer = $('<img width="25px" height="25px" src="http://i.imgsafe.org/c07fe0155d.gif" data-x="" data-y=""></img>');
obj.replaceWith(replacer);
var found = $("#gameArea").find("img");
setTimeout(function(){
    var revert = '<div class="grass gameTile" data-component="" data-x="changex" data-y="changey"></div>';
    var x = revert.replace("changex", String(x_cord[0]));
    x_cord.splice(0,1);
    var y = revert.replace("changey", String(y_cord[0]));
    y_cord.splice(0,1);
    $(found[0]).replaceWith(revert);
}, 1200);

}

2 个答案:

答案 0 :(得分:1)

什么是x_cord和y_cord? 无论如何,为了应用替换它应该是

setTimeout(function(){
var revert = '<div class="grass gameTile" data-component="" data-x="changex" data-y="changey"></div>';
revert = revert.replace("changex", String(x_cord[0]));
x_cord.splice(0,1);
revert = revert.replace("changey", String(y_cord[0]));
y_cord.splice(0,1);
$(found[0]).replaceWith(revert);
}, 1200);

您没有设置revert的值,所以当您更改它时,您可以定义任意变量。那不做任何事情。

答案 1 :(得分:0)

您可以将模板文字替换为.replace()

&#13;
&#13;
var x_cord = [123],
  y_cord = [456];

var revert = `<div class="grass gameTile" 
                       data-component="" 
                       data-x="${x_cord[0]}" 
                       data-y="${y_cord[0]}">
                  </div>`;
                  
$("img").replaceWith(revert);

console.log($(".grass").data())
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img>
&#13;
&#13;
&#13;

相关问题