在document.ready中使用jquery更改标记的属性

时间:2012-03-02 06:04:39

标签: jquery

我有一个button input,我打算像这样禁用它:

$(document).ready(function() {
                if ($('#participants tr').length < 3 )
                    jQuery("#send").attr('disabled', true);
                else
                    jQuery("#send").attr('disabled', false);
            });

它成功禁用,但当启用条件为真时,此部分以嵌套方式复制:

修改

<form>
 <fieldset>
 <table id="participants">
  ....
 </table>
  </fieldset>
</form>

<input type="button" value="send" onClick="sendMail()" id="send" />
<fieldset>
...
<form>
 <table id="participants">
    <tr>
      <td><a onClick='f(id)' >del</a></td>
    </tr>
 </table>
</form>
</fieldset>
<input type="button" value="send" onClick="sendMail()" id="send" />

这个table有一些参与者行,每行都有一个del链接,单击它会导致从数据库和表中删除参与者,当表中的行数小于3时我将禁用{{ 1}} 为什么呢?

3 个答案:

答案 0 :(得分:1)

尝试removeAttr

$(document).ready(function() {
                if ($('#participants tr').length < 3 )
                    jQuery("#send").attr('disabled', disabled);
                else
                    jQuery("#send").removeAttr('disabled');
            });

<强>更新

我不知道你想要实现什么,你没有默认禁用该按钮,所以在DOM准备就绪它没有意义我必须遗漏一些东西,但是从你提供的代码和我的从中可以理解,如果你将标记修改为

<form>
 <fieldset>
 <table id="participants1">
  <tr>
      <td>1</td>
    </tr>
     <tr>
      <td>2</td>
    </tr>
     <tr>
      <td>3</td>
    </tr>
 </table>
  </fieldset>
    <input type="button" value="send" onClick="sendMail()" class="send" />
</form>
<fieldset>
<form>
 <table id="participants">
    <tr>
      <td>only one</td>
    </tr>
 </table>
    <input type="button" value="send" onClick="sendMail()" class="send" />
</form>
</fieldset>

请注意,这些ID现在是唯一的,我已将类send应用于每个发送按钮,同时我已经在表单中使用了发送按钮。 jquery部分如下

$("form").each(function(){
 var $this = $(this);
 var trCount = $this.find("table tr").length;
    console.log(trCount);
    if(trCount>2){
        console.log($this.find(".send"));
    $this.find(".send").attr("disabled","disabled");
    }//else do nothing        
});

上面代码中发生的事情是它遍历页面上的所有表单元素并在其中查找表,然后检查行计数,如果超过指定的长度则禁用该表单的按钮..

DEMO

答案 1 :(得分:0)

检查出来: http://jquery-howto.blogspot.in/2008/12/how-to-disableenable-element-with.html

//启用

$('#send').removeAttr('disabled');

//或者您可以将attr设置为&#34;&#34;

$('#send').attr('disabled', '');

答案 2 :(得分:0)

而不是

        if ($('#participants tr').length < 3 )
            jQuery("#send").attr('disabled', true);
        else
            jQuery("#send").attr('disabled', false);

尝试

$('#participants').each(function(){

      if ($(this).find('tr').ength < 3 )
             $(this).parents('fieldset').next("#send").attr('disabled', true);
      else
             $(this).parents('fieldset').next("#send").attr('disabled', false);

});