简体   繁体   English

如何使用jQuery选择HTML属性?

[英]How do I select an HTML attribute with jQuery?

I added a custom attribute to a Textbox: 我向文本框添加了自定义属性:

<asp.TextBox MyCustomAttribute="SomeValue"><asp.TextBox>

And I'd like to access that value from inside an AJAX success function if possible. 而且,如果可能的话,我想从AJAX成功函数内部访问该值。

Also note that I've left off any attributes and parameters that aren't relevant to my question. 另请注意,我已经省略了与我的问题无关的所有属性和参数。

I'm using AJAX inside of a jQuery change() function so when users update the value in the textbox it updates the database without posting back and I have that much already working. 我在jQuery change()函数中使用AJAX ,所以当用户更新文本框中的值时,它会更新数据库而不会回发,并且我已经做了很多工作。

Once I'm inside the context of my change() function, I set the value of MyCustomAttribute to a variable so I can (theoretically) access it from inside the AJAX success function: 一旦进入change()函数的上下文,就将MyCustomAttribute的值设置为一个变量,以便(理论上)可以从AJAX成功函数内部访问它:

.change(function () {
  var MyCustomAttribute = $(this).attr("MyCustomAttribute");
  $.ajax({
    success: function (response) {
      if (response.d == "SUCCESS") {
        // here I just want to see if I can access the value
        // of MyCustomAttribute so I'm trying to set it to a
        // variable and do an alert()
        var DidItWork = $("input[MyCustomAttribute='" + MyCustomAttribute + "']");
        alert(DidItWork);
  });
});

But so far it's not working, I've tried typing my jQuery select for my DidItWork variable a few different ways, but instead of displaying SomeValue like I was hoping, my alert displays [object Object] or [undefined] . 但到目前为止,它不工作,我试着输入我的jQuery选择我DidItWork可变几种不同的方法,但不是显示SomeValue像我希望,我的警告显示[object Object][undefined] I tried it with and without a .val() at the end, but that makes the alert display the value that's in the textbox, not the value of MyCustomAttribute . 我尝试了在结尾处不带.val()情况,但这使警报显示文本框中的值,而不是MyCustomAttribute的值。

Anyway I'm not sure what part of the syntax I'm getting wrong, can anyone help? 无论如何,我不确定我弄错了语法的哪一部分,有人可以帮忙吗?

According to this link , you can use attr() inside of jQuery to manipulate HTML attributes. 根据此链接 ,您可以在jQuery中使用attr()来操纵HTML属性。

You should assign the text box an id and use jQuery to get that element and modify its attributes using attr(). 您应该为文本框分配一个ID,并使用jQuery获取该元素并使用attr()修改其属性。

An example line of code is: 示例代码行是:

$('#textBox').attr('MyCustomAttribute', 'SomeNewValue');

Try to find asp.TextBox by class like this: 尝试按如下所示的类查找asp.TextBox:

<asp.TextBox class="tb" MyCustomAttribute="SomeValue"><asp.TextBox>


.change(function () {
  $.ajax({
    success: function (response) {
      if (response.d == "SUCCESS") {
        var DidItWork = $(".tb").attr("MyCustomAttribute");
        alert(DidItWork);
  });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM