jquery获取并将href传递给函数

时间:2013-06-17 21:15:03

标签: javascript jquery

我在获取点击元素的href并将其传递给函数时遇到了一些问题,这是我以前没有做过的事情,所以尽我所能但却没有得到它。有什么想法吗?

$('#smoke_confirm').click(function(e){
            var href = $(this).attr("href");
            tstconfirm(href);
            e.preventDefault();
        });

        function tstconfirm(href){
            smoke.confirm('Are you sure you want to delete?',function(e){
                if (e){
                    window.location = $(href);
                }
            }, {cancel:"cancel", ok:"confirm"});
        }

2 个答案:

答案 0 :(得分:2)

href这里是一个文本,因此$(href)不正确,因为它会尝试选择具有href值的元素。只做window.location = href。另外,如果你只想获得href,你不需要创建this的jquery实例,你可以只做this.href这是一个DOM元素属性。

$('#smoke_confirm').click(function(e){
            var href = this.href;
            tstconfirm(href);
            e.preventDefault();
        });

        function tstconfirm(href){
            smoke.confirm('Are you sure you want to delete?',function(e){
                if (e){
                    window.location = href;
                }
            }, {cancel:"cancel", ok:"confirm"});
        }

答案 1 :(得分:1)

href是一个字符串

 window.location = $(href); // This will try to convert it to a jQuery object

应该是

 window.location = href;