2

我很难在我的转发器控件中找到文本框值。单击按钮时,我需要获取与单击的按钮内部的文本框相对应的文本框值。

所以我有 :

Textbox1 ---> 必须与 Button1 绑定 TextBox2 ----> 与 Button2 绑定

<span>Question :</span><span>my second content <br /></span><span>Answer : </span><input name="ctl00$MainContent$ctl00$ctl00$TextArea" type="text" id="MainContent_ctl00_TextArea_0" value="6454" />

添加问题


问题:abcddf
答案:添加问题

现在我有 jquery 函数,它被点击:

 $(".addAnswerButton").click(function () {

        //var quantityBox = $("#TextArea", $(this).parent());
        var tr = $(this).closest("text")
        alert(tr.val());
        //quantityBox.text = "Hello there";
        //var currentValue = quantityBox.val();
        $(this).siblings('input[type="text"]').first().val("clicked");

        //quantityBox.val(parseInt(currentValue) + 1);
    });

我已经让它部分工作:

$(this).siblings('input[type="text"]').first().val("clicked");

我在哪里设置文本框文本,但是再一次,如果我单击第二个按钮,什么也没有发生。

我做错了什么?如何从特定文本框中获取价值?

更新

现在我采用向每个控件添加自定义属性的解决方案:

    <span>Question :</span>
<span>my second content <br /></span>
<span>Answer : </span>
<input name="ctl00$MainContent$ctl00$ctl00$TextArea" type="text" id="MainContent_ctl00_TextArea_0" value="654" mydataid="2" />

    <button id="MainContent_ctl00_answerQuestion_0" Class="addAnswerButton" onclick="Click()" mydataid="2" >Add Question</button><hr /><span>Question :</span><span>abcdedf <br /></span>

    <span>Answer : </span><input name="ctl00$MainContent$ctl00$ctl01$TextArea" type="text" mydataid="1" id="MainContent_ctl00_TextArea_1" value="654" />

    <button id="MainContent_ctl00_answerQuestion_1" Class="addAnswerButton" onclick="Click()" mydataid="1">Add Question</button>​

所以现在我可以通过这样做从 onclick 事件中获取自定义属性:

$(".addAnswerButton").click(function() {
    var pos = $(this).attr("mydataid");
    alert(pos);
 //   $(this).siblings('input[type="text"]').first().val("clicked");
});

但是我如何获得具有相同自定义属性名称作为按钮的文本框控件?

更新 2

经过 70 次尝试后,我终于弄明白了(我第一次尝试使用 Jquery)

解决方案

$(".addAnswerButton").click(function() {
    var pos = $(this).attr("mydataid");
    results = $('input[type = "text"][mydataid="'+pos+'"]').first();
    alert(results.val());
});

所以重点是,您正在获取自定义属性“名称”,然后搜索具有相同属性名称的文本框。

4

2 回答 2

2

您可以使用某些属性从服务器标记它们并在您的 jQuery 代码中使用它。

服务器的输出将是这样的:

<input type='text' data-item-id='1'>First</input>
<inpyt type='button' data-item-id='1'></input>

 <input type='text' data-item-id='2'>Second</input>
    <inpyt type='button' data-item-id='2'></input>

按下按钮后,获取它的 data-item-id 并搜索具有相同属性值的文本框。

于 2012-09-21T14:00:21.443 回答
1

评论后编辑。

我前往您的 jsfiddle 并使其与此一起使用:

$('[id*="answerQuestion"]').click(function () {
    $(this).parent().children('[id*="TextArea_' + $(this).attr('id').substring($(this).attr('id').length - 1) + '"]').val('clicked');
});

解释:

  1. 我意识到你的 id 是按钮的 answerQuestion 和 txt 的 TextArea。
  2. 在函数中,我制作了一个使用 TextArea id 的选择器(子字符串将索引添加到它)

而已!这有点棘手,但这是我找到的最佳解决方案。

希望这可以帮助!

问候,如果有一些英文不一致,对不起:)!

于 2012-09-21T14:16:55.890 回答