使用javascript从带有链接/按钮的元素中获取值

使用javascript从带有链接/按钮的元素中获取值,javascript,jquery,Javascript,Jquery,当我点击id为bob的链接时,我希望它关闭聊天,同时给出下面显示的隐藏输入值 <div id="chat" class="chat"> <div id="ch" class="ch"> <label id="name1">bob</label> <a id="bob" onclick="closechat(this.id)">x</a> <--- LINK I CLICK O

当我点击id为bob的链接时,我希望它关闭聊天,同时给出下面显示的隐藏输入值

<div id="chat" class="chat">
    <div id="ch" class="ch"> 
        <label id="name1">bob</label>
        <a id="bob" onclick="closechat(this.id)">x</a>  <--- LINK I CLICK ON 
    </div>
    <input type="hidden" name="to" id="to" value="bob">  <-- HIDDEN VALUE I WANT 
    <input type="hidden" id="chatboxid" value="chatbox"> 
    <div class="chatbox" id="chatbox" style="display: none; "> 
        <div class="messages"></div>
        <textarea name="message" id="message" class="chatinp" rows="3" cols="27">
        </textarea>
        <button class="send" onclick="submitmessage()">Send</button>
    </div>
</div>

上下快速移动

x假设
上的
id
属性

  • 您不能重用
    ID
    属性值;它们必须是独一无二的。帮自己一个忙,使
    div#chat
    元素
    ID
    唯一,并将
    rel=“chat111”
    与父
    元素的
    ID
    相等。您可以从
    a
    标记遍历
    .chat
    ,但这可能是不必要的。通过我的评论或其他方式?@Ryan:如果@Jared回答了问题,请在您的评论中注明。如果你自己解决了这个问题,请自己发布答案并接受。@jarad你的帮助和我的帮助:-)
    function closechat(id) {
        var value_you_want = $('#' + id).closest('.chat').find('input[name=to]').val();
        //...
    }
    
    <div class="chat">
        <div class="ch"> 
            <label>bob</label>
            <a class="closechat">x</a>  <--- LINK I CLICK ON 
        </div>
        <input type="hidden" name="to" value="bob">  <-- HIDDEN VALUE I WANT 
        <div class="chatbox" style="display: none; "> 
            <div class="messages"></div>
            <textarea name="message" class="chatinp" rows="3" cols="27">
            </textarea>
            <button class="send">Send</button>
        </div>
    </div>
    
    <script type="text/javascript">
        $('a.closechat').click(function() {
            // what closechat() does goes here and it should use
            // `this.id` instead of getting an argument.
        });
        $('button.send').click(function() {
            // What submitmessage() does goes here, it too looks at
            // `this` to to figure out where it is and which <textarea>
            // to use.
        });
    </script>