jQuery切换不使用this.name

时间:2013-09-30 12:59:58

标签: javascript jquery forms

我已经创建了一个带验证的联系表单,并尝试使用帮助功能,以便有人点击问号并弹出一个带有解释的div。

我找到了一种方法,使用变量和“this”选择器,它似乎工作正常,但它已停止工作,我似乎无法阻止默认的#行为。

看过类似的问题,没有任何迹象表明问题可能是什么。这是功能:

$(function() {
    //show/hide
    $('a.form-question-help-link').click(function(event) {
        event.preventDefault();
        var divname= this.name;
        $("#"+divname).toggle();
        return false;
});

});

jsFiddle链接:http://jsfiddle.net/dvmac/dpVzL/2/

3 个答案:

答案 0 :(得分:1)

#选择器基于id选择。如果要选择名称,则需要属性slector:'[name="' + divname + '"]'

$('a.form-question-help-link').click(function(event) {
    event.preventDefault();
    var divname= this.name;
    $('[name="' + divname + '"]').toggle();
    return false;
});

更好的方法是执行此操作:$(this)

$('a.form-question-help-link').click(function(event) {
    event.preventDefault();
    $(this).toggle();
    return false;
});

如果你有动态创建的元素,那么你可能想尝试这个:

$(document).on('click', 'a.form-question-help-link', function(e) {
    $(this).toggle();        
    e.preventDefault();
});

答案 1 :(得分:0)

使用$(this).attr('name')$(this).prop('name')

检查this小提琴。

答案 2 :(得分:-3)

should be $(this) instead of this

$(function() {
        //show/hide
        $('a.form-question-help-link').click(function(event) {
            event.preventDefault();
            var divname= $(this).name;
            $("#"+divname).toggle();
            return false;
    });

    });