我有以下JavaScript代码,我喜欢替换一些字符串,但我不能
$new_slide = '<div class="slide">' +
'<table>' +
'<tr>' +
'<td class="pictureContainer">' +
'<img src="/img/admin/slide-placeholder.svg" />' +
'<input type="hidden" name="slides[0][picture][id]" data-value="picture_id" />' +
'<input type="hidden" name="slides[0][picture][thumbnail]" data-value="picture_thumbnail" />' +
'<input type="hidden" name="slides[0][picture][original]" data-value="picture_original" />' +
'</td>' +
'<td class="fieldsContainer">' +
'<p>' +
'<label for="masthead_0">Masthead</label>' +
'<input type="text" data-value="masthead" name="slides[0][masthead]" id="masthead_0" />' +
'</p>' +
'<p>' +
'<label for="first_heading_0">Heading #1</label>' +
'<input type="text" data-value="first_heading" name="slides[0][first_heading]" id="first_heading_0" />' +
'</p>' +
'<p>' +
'<label for="second_heading_0">Heading #2</label>' +
'<input type="text" data-value="second_heading" name="slides[0][second_heading]" id="second_heading_0" />' +
'</p>' +
'<p>' +
'<label for="link_title_0">Link title</label>' +
'<input type="text" data-value="link_title" name="slides[0][link][title]" id="link_title_0" />' +
'</p>' +
'<p>' +
'<label for="link_url_0">Link URL</label>' +
'<input type="text" data-value="link_url" name="slides[0][link][url]" id="link_url_0" />' +
'</p>' +
'</p>' +
'<label for="target_0">Link Target</label>' +
'<select id="target_0" data-value="link_target" name="slides[0][link][target]">' +
'<option value="_self">' + z.self + '</option>' +
'<option value="_blank">' + z.blank + '</option>' +
'</select>' +
'</p>' +
'</td>' +
'</tr>' +
'</table>' +
'</div>';
var slide = {
"picture_id" : "45",
"picture_thumbnail" : "/thumbnail.jpg",
"picture_original" : "/original.jpg",
"masthead" : "Mast Head #1",
"first_heading" : "First Heading",
"second_heading" : "",
"link_title" : "Link Title #1",
"link_url" : "Link URL #1",
"link_target" : "Link target #1"
}
for(field in slide)
{
$new_slide.replace('data-value="' + field + '"', 'value="' + slide[field] + '"');
}
更多特色,
我喜欢通过迭代slide
变量来将$new_slide
变量中的“关键”值替换为value
变量中的slide
。
反过来,刺痛
<input type="hidden" name="slides[0][picture][id]" data-value="picture_id" />
我喜欢转换成
<input type="hidden" name="slides[0][picture][id]" data-value="45" />
以及该领域
<input type="text" data-value="second_heading" name="slides[0][second_heading]" id="second_heading_0" />
我喜欢转换成
<input type="text" data-value="" name="slides[0][second_heading]" id="second_heading_0" />
但我的代码似乎无法正常工作。有人可以帮助我吗?
答案 0 :(得分:2)
你必须改变它:
$new_slide = $new_slide.replace('data-value="' + field + '"', 'value="' + slide[field] + '"');
因为replace
函数不会更改$new_slide
值,所以它只返回新修改的字符串。