开发者

jquery - regex trouble using .match

Best explained with an example you can fiddle with: http:/开发者_开发问答/jsfiddle.net/F4H46/

To summarize:

(a) JQuery script is fired by clicking an anchor tag.

(b) Desired result: get chars following the href id=? and save to variables

(c) $(this)[0] does contain the correct href

(d) Using .match(regex) to strip off the desired chars creates a 404 error.

Why a 404 error? The .match(regex) works PERFECTLY if the same string is hard-coded.


$("a").bind('click', function(e) {
    e.preventDefault();  
    var xxx = $(this).attr('href');
    alert(xxx);
    var yyy = xxx.match(/\=(\d*)(\w*)/);
    alert(yyy[0]);
    alert(yyy[1]);
    alert(yyy[2]);
});


When you click the anchor tag, the page will automatically change the href of the page, causing a 404 cause the page doesn't exist. First thing to do after the anchor tag is clicked is: e.preventDefault(), preventing the page from getting redirected.

$("a").click(function(e){
    e.preventDefault();
    // rest of the code
});


Youse this:

<script type="text/javascript">
$("a").click(function()
{   var xxx = $(this).attr('href');
        alert(xxx);
    var yyy = xxx.match(/\=(\d*)(\w*)/);
    alert(yyy[0]);
    alert(yyy[1]);
    alert(yyy[2]);
});
</script>

This working, difference is that you need to use attr('href');

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜