如何选择textarea并检查它是否只读?

时间:2013-02-04 23:21:02

标签: javascript jquery html

我正在努力使用jQuery。我想编写一个脚本,当单击该按钮时,该脚本检查与按钮共享同一父项(列表项)的文本区域是否为只读。这是HTML:

...
<li>
  <h1>Title</h1>
  <button type="button" onclick="javascript:confirmDelete();">Delete</button>
  <button type="button" onclick="javascript:toggle();">Toggle</button>
  <textarea class="readOnly" readonly="true">Some text</textarea>
</li>
...

脚本:

<script language="JavaScript">
  <!--
  ...    
  function toggle()
  {
    var textArea = $(this).parent("li").children("textarea");
    var isReadOnly = textArea.attr("readonly");
    if (isReadOnly == "true") {
      alert('It\'s read-only.');
    } else {
      alert('It\'s not read-only.');
    }
  }
  //-->
</script>

看来我无法通过var textArea = ...

更新1:

好的,我打破了选择,以帮助自己分析问题:

...
var btn = $(this);
console.log(btn); //returns value, but not sure what exactly
var li = btn.parent();
console.log(li); //returns value, but not sure what exactly
var textArea = li.children('textarea');
console.log(textArea.prop('tagName')); //returns unidentified

所以,有错误。我似乎无法理解究竟是什么问题,因为如果我从调试中获得的所有输出都是一个对象(我甚至不知道它代表什么,它是元素还是数组),我就无法学到很多东西。 ..)或unidentified。 jQuery并不完全直观。

3 个答案:

答案 0 :(得分:0)

该属性区分大小写。尝试改为

var isReadOnly = textArea.attr("readOnly");

答案 1 :(得分:0)

如果它是您可能需要的唯一:

...find("textarea")[0];

...children("textarea");

或只是$(this).siblings("textarea")[0];

或直接选择

var mylist = $(this).siblings("textarea.readOnly");

if (mylist.length > 0)//true if it is

答案 2 :(得分:0)

这里有一些错误。

首先,事实证明,当属性“readonly”处于活动状态时,它没有“true”值,而是“readonly”值。

另一方面,如果你通过onclick调用一个函数(并且我不是100%肯定),你就不能使用$(this)。我建议你这样做(在给触发按钮提供一些ID之后,或任何识别它的东西):

$(function() {

  $("button#my-button").bind("click", function() {
    if ($(this).siblings("textarea").attr("readonly") == "readonly") {
      alert("It's readonly");
    } else {
      alert ("It's not");
    }
  });

});
相关问题