【问题标题】:Attach a button action to the div it's inside?将按钮操作附加到它所在的 div 上?
【发布时间】:2011-07-31 18:39:13
【问题描述】:

编辑我实际上是在问我是否可以定位 div 我的按钮是 里面不知道id的名字?

我想编写一个 javascript 函数来更改 INPUT 框和按钮本身的属性,但我想这样做而不为每个按钮和每个输入框创建唯一的 id。

假设我有一个这样的 onclick javascript

function changeid ()
{
var e = document.getElementById("changebutton");
e.id = "savebutton";
$('#TheAttachedDiv').attr('readonly', false);
}
function changeid ()
{
var e = document.getElementById("savebutton");
e.id = "changebutton";
$('#TheAttachedDiv').attr('readonly', true);
}

因为其他原因我将有 4 个具有相同类的字段,所以我不希望在单击除一个 div 之外的按钮时更改所有 CHANGE 按钮和 DIVS 的属性。

有没有办法做到这一点? 谢谢

我在做什么:

<div class="question active">Q1
  <input id="one" type="text">
</div>
<div class="button passive">
  <input type="button" value="Change" id="changeone" onclick="changeid()">
</div>

同一个 div 不断重复。

【问题讨论】:

  • 您使用的是什么 html 标记?

标签: javascript jquery html


【解决方案1】:

如果您想要直接父级,请尝试使用 jQuery 方法 .parent(),如果您想要搜索 DOM 树更高的祖先,请尝试使用 .parents( ... )

【讨论】:

    【解决方案2】:

    应该是这样的

    jQuery('.field_same_class').click(function(){
        if(jQuery(this).attr('readonly')==false)
        {
            jQuery(this).attr('readonly',true);
            jQuery(this).next('.button_class').attr('readonly',true);
        } else {
            jQuery(this).attr('readonly',false);
            jQuery(this).next('.button_class').attr('readonly',false);
        }
    });
    

    【讨论】:

    • 我会试试这个并告诉你:)
    • 不,但这太棒了。我实际上是在寻找下面发布的 .parent() 函数。无论如何,非常感谢您的宝贵时间!这段代码看起来很棒!
    猜你喜欢
    • 2014-09-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-18
    • 2010-12-28
    • 1970-01-01
    • 2017-04-11
    • 1970-01-01
    相关资源
    最近更新 更多