使用单引号传递参数

时间:2014-12-15 13:36:59

标签: javascript jquery html

我正在使用此代码段

str += '<div class="section clear">' + 
    '<span><img src="' + pic_square + '" alt="" width="32px" height="32px" /></span>' + 
    '<span class="user_name">' + rows.data[i].name + '</span>' + 
    '<a href="#" class="blue_button blue_button_small flt_right" style="line-height: 16px; height: 18px; margin: 6px 15px 0 0;" onclick="showSelected(' + details + '); return false;">Select</a>' + 
'</div>';

这里的细节参数可能包含单引号。在这种情况下,它显示错误。我该如何解决这个问题?

3 个答案:

答案 0 :(得分:1)

获取可能包含单引号的所有变量,并将以下内容应用于它们:

str = str.replace(/(['"])/g, "\\$1");

这将逃脱你的所有报价。然后,您可以按原样使用函数中的变量。

或者您可以创建一个函数来执行此操作:

function escapeStrQuotes(str)
{
  return str.replace(/(['"])/g, "\\$1");
}

然后像这样使用:

str += '<div class="section clear">' + 
    '<span><img src="' + escapeStrQuotes(pic_square) + '" alt="" width="32px" height="32px" /></span>' + 
    '<span class="user_name">' + escapeStrQuotes(rows.data[i].name) + '</span>' + 
    '<a href="#" class="blue_button blue_button_small flt_right" style="line-height: 16px; height: 18px; margin: 6px 15px 0 0;" onclick="showSelected(' + escapeStrQuotes(details) + '); return false;">Select</a>' + 
'</div>';

答案 1 :(得分:1)

让jQuery执行转义变量内容的繁重工作:

&#13;
&#13;
// for testing purposes
var pic_square = '#',
    rows = {
      data: [{name:'foo'}]
    },
    details = 'bla',
    i = 0;

function showSelected(details)
{
  alert(details);
}

$('<div class="section clear"> \
    <span><img alt="" width="32px" height="32px" /></span> \
    <span class="user_name"/> \
    <a href="#" class="blue_button blue_button_small flt_right" style="line-height: 16px; height: 18px; margin: 6px 15px 0 0;">Select</a> \
</div>')
  .find('img')
    .attr('src', pic_square)
    .end()
  .find('.user_name')
    .text(rows.data[i].name)
    .end()
  .find('a')
    .on('click', (function(details) {
      return function(e) {
        e.preventDefault();
        showSelected(details);
      };
    }(details)))
    .end()
  .appendTo('#container');
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container"></div>
&#13;
&#13;
&#13;

答案 2 :(得分:1)

使用jQuery很容易!

所有这些HTML和Regex的混合都不好。你正在使用jQuery,只需用jQuery方式。

此外,我不确定为什么参数会有撇号,但如果它的值为1,则尝试使用.apply

在循环中创建元素并分配信息所在的位置。它简单如下:

var details = rows.data[i].details, //  simply guessing at some form of how you got your param
    //  beging creating your elements. First, the div.section, which appears to be your wrapper, this will come into play later
    section = $('<div />', { class: 'section clear' }),
    //  now to create the image element. I know yours is wrapped in a span, but I'll show you a quick add for that a little later
    img = $('<img />', { alt: '', height: '32', src: pic_square, width: '32' }),
    //  now for your username span, I'm assuming this is your label
    userName = $('<span />', { class: 'user_name', text: rows.data[i].name }),
    //  here I create your link, notice I don't add the "onclick" method yet, just wait,
    //  going to show you use of apply
    lnkSelect = $('<a />', {
        class: 'blue_button blue_button_small flt_right',
        href: 'javascript:void(0)',
        style: 'line-height: 16px; height: 18px; margin: 6px 15px 0 0;',
        text: 'Select'
    });

//  Here is where it all comes together
//  jQuery's append/prepend methods are very powerful,
//  Notice you can join multiple elements in another with just simple comma separation,
//  You'll also notice that IMG span wrapper I was talking about earlier coming back!
section.append(
    //  First element in your div.section is the image, but alas! we need that SPAN tag around it!
    //  I simply use jQuery to create a SPAN tag and then append the image to it! Viola!
    $('<span />').append(img),
    //  Now to append that username span
    userName,
    //  finally, add the link clicker!
    lnkSelect
).appendTo($('body'));  //  this Trixy part is like "append", except it adds this element to whatever we pass in the selector! Thus, "appendTo"

//  Finally! The onclick value!
//  Since you mentioned some trixy stuff with the "details",
// I make use of ".apply", which you can pass parameters
//  through as a value in an array in the second param of apply
//  see more at: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply
lnkSelect.on('click', function(e) { showSelected.apply(this, [details]) })

举一个简单的例子,在这里使用您的值类型和我的代码,运行下面的代码段!

&#13;
&#13;
$(function() {
	var pic_square = '../img/logo.png',
	rows = {
		data: [
			{ name: 'Bob', details: "Bob'sPlace" },
			{ name: 'Diana', details: "Diana's Shack" },
			{ name: 'Jerry', details: "Jerry Atric's Mind Blowing" } ]
	},
	str = '';
	
	function showSelected(value) {
		alert(value);
	}
	
	$.each(rows.data, function(i) {
		var details = this.details,
			section = $('<div />', { class: 'section clear' }),
			img = $('<img />', { alt: '', height: '32', src: pic_square, width: '32' }),
			userName = $('<span />', { class: 'user_name', text: this.name }),
			lnkSelect = $('<a />', {
				class: 'blue_button blue_button_small flt_right',
				href: 'javascript:void(0)',
				style: 'line-height: 16px; height: 18px; margin: 6px 15px 0 0;',
				text: 'Select'
			});
		
		section.append(
			$('<span />').append(img),
			userName,
			lnkSelect
		).appendTo($('#BODY')); // using a div with the id "BODY"
		
		lnkSelect.on('click', function(e) { showSelected.apply(this, [details]) })
	})
})
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="BODY"></div>
&#13;
&#13;
&#13;