链接jquery函数 - 初学者

时间:2016-06-18 19:52:14

标签: javascript jquery

我正在尝试在单击单选按钮时设置元素的名称和ID。为避免重复选择器,我尝试将其设置为:

$( "#selectOther" ).click(function() {
    $( "[field=primaryInput]" ).attr('id', "modifiedId", function() {
        $(this).attr('name', "modifiedName");
        if ($(this).attr('visible') == "False") {
            $(this).slideDown('fast');
            $(this).attr("visible", "True");
        }
    });
});

但是,它不起作用。似乎ID已更改,但Name不是,也不是函数的其余部分已执行。有人可以帮我理解如何正确表达这个吗?

这里是JFiddle

编辑:在我的最后一个案例中,我会有几个按钮显示该字段是否被隐藏,而其他按钮会隐藏它,如果它是可见的。这就是我没有使用.slideToggle()

的原因

1 个答案:

答案 0 :(得分:2)

See this fiddle:

$('input[type="radio"]').click(function() {
  $('input[data="primaryInput"]')
    .prop('id', this.id)
    .prop('name', this.name)
    .val(this.value)
    .css('display', 'inline-block');
});

Number of points:

  1. You didn't set an external resource (namely jQuery) in your fiddle - so you wouldn't ever get jQuery functions to execute
  2. Use the data attribute for custom attributes. You can access them the way I have done or by selecting the $(element).data('field')

This example might help you understand how chaining works. One other piece of advise is that chaining only works if the method invoked next receives the same element the previous method returns. If it ever changes, you can use end() to get the previous state.

相关问题