开发者

escaped char generating "missing ) after argument list" error?

开发者 https://www.devze.com 2023-03-10 05:15 出处:网络
This little line of code here is fr开发者_运维知识库om a shopping cart: <a href=\"javascript:;\" onclick=\"simpleCart.add( \'name=The Devil&#039;s Sneakers\', \'price=10\', \'shipping=0\', \'q

This little line of code here is fr开发者_运维知识库om a shopping cart:

<a href="javascript:;" onclick="simpleCart.add( 'name=The Devil&#039;s Sneakers', 'price=10', 'shipping=0', 'quantity=1' );">Add To Cart</a>

Firebug's console shows: "missing ) after argument list". Clearly the ')' isn't missing! But I suspect it has something to do with the escaped char

&#039;

since the other similarly formatted links without apostrophes in the name= argument are working fine.

Thoughts?


onclick="simpleCart.add( 'name=The Devil&#039;s Sneakers'...

Is an HTML attribute with the apostrophe escaped at an HTML level. It is exactly the same as saying:

onclick="simpleCart.add( 'name=The Devil's Sneakers'...

with the obvious problem with the string closing too early. HTML-escaping doesn't help you because the HTML-escape is only needed to encode the characters that are special to HTML. That would include a double-quote character but not a single quote, since you've used double-quotes to delimit the attribute value.

The apostrophe isn't special to HTML here, but it is to JavaScript. You need to use JavaScript string literal escaping, and in that kind of escaping you need backslashes:

onclick="simpleCart.add( 'name=The Devil\'s Sneakers'...

Either way, it's clear that escapes inside other escapes are really confusing and this is another good reason not to use inline event handler attributes. Instead, in plain JavaScript:

<button type="button" id="foo">Add to cart</button>
<script type="text/javascript">
    document.getElementById('foo').onclick = function() {
        simpleCart.add("name=The Devil's Sneakers", 'price=10', 'shipping=0', 'quantity=1');
    };
</script>

(I used a button because what you've got isn't a link that goes anywhere. You can style it to look like a link instead of a button if you prefer, but it's better not to have a link if none of the normal affordances of links, like middle-click or right-click-bookmark make any sense.)


Escape apostrophes with \x27. This code should work:

<a href="javascript:;" onclick="simpleCart.add( 'name=The Devil\x27s Sneakers', 'price=10', 'shipping=0', 'quantity=1' );">Add To Cart</a>


Try \' instead of &#039;

It works well.

<html>
<body>
<a href="javascript:;" onclick="alert('The Devil\&#039;s Sneakers');">Add To Cart</a>
<a href="javascript:;" onclick="alert('The Devil\'s Sneakers');">Add To Cart</a>
</body>
</html>
0

精彩评论

暂无评论...
验证码 换一张
取 消