草庐IT

关于 javascript:jQuery .prop() 返回未定义,而 .attr() 对数据按预期工作-*

codeneng 2023-03-28 原文

jQuery .prop() returns undefined, while .attr() works as expected for data-*

我只是想从两个元素中获取几个属性。从 input 元素获取属性 value 可以按预期工作。问题在于从 button 元素获取属性 data-detail 属性。使用 .prop() 时返回 undefined,但使用 .attr().

时按预期工作

谁能解释我目睹的这种奇怪行为?

HTML

1
2
3
4
5
6
7
    <label for="firstName">First name</label>
   
        <button id="editFirstName" class="btn ctaBtn greenBtn editBtn">Edit</button>
        <button class="btn ctaBtn greenBtn saveBtn" data-detail="firstName">Save</button>
        <button id="closeFirstName" class="btn ctaBtn greyBtn closeBtn">Close</button>
   
    <input type="text" id="firstName" name="firstName" value="[+firstName+]" readonly>

JS

1
2
3
4
5
6
7
8
9
$(".saveBtn").on("click", function() {
    var saveBtn = $(this);
    // The following statement yields undefined. When using .attr() it works as expected.
    var detail = saveBtn.prop("data-detail");
    var relevantInput = saveBtn.parent().next();
    // The following statement works as expected.
    var value = relevantInput.prop("value");
    // ...
});

  • 你用的是什么版本的jquery?
  • @LearningPhase jquery-1.11.3.min.js
  • 对于数据属性,我建议使用 saveBtn.data("detail")
  • @misher 我对此一无所知,谢谢 - 它确实按预期工作。
  • @LearningPhase 不是我的数据详细信息被视为属性吗?如果不是,为什么不呢?


那是因为 HTML 元素上没有 data-detail 属性。

以下是 .data()、.prop() 和 .attr() 的简要说明:
DOM 元素是一个具有 methodsproperties(来自 DOM)和 attributes(来自渲染的 HTML)的对象。其中一些 properties 通过 attributes id->id, class->className, title->title, style->style etc. 获得他们的 initial value
考虑这个元素:<input type="checkbox" checked data-detail="somedata" >
以下结果将是:

1
2
$('input').prop('id'); // =>""-empty string, property id exist on the element (defined by DOM) , but is not set.
$('input').attr('id');// => undefined - doesn't exist.

如果您执行以下操作:

1
2
3
$('input').attr('id',"someID");
$('input').prop('id'); // => "someID"
$('input').attr('id'); // => "someID"

还有:

1
2
3
$('input').prop('id',"someOtherID");
$('input').prop('id');// => "someOtherID"
$('input').attr('id');// => "someOtherID"

So, some attributes and properties have 1:1 mapping. (change of
the attr result change of the prop and vice versa).

考虑以下内容:<input type="text" data-detail="somedata" value="someValue">

1
2
3
$('input').prop('value'); // => "someValue"
$('input').val();         // => "someValue"
$('input').attr('value'); // => "someValue"

如果你这样做:

1
2
3
4
5
6
7
8
9
$('input').prop('value','newVal');

// or

$('input').val('newVal');

$('input').prop('value'); // =>"newVal"    -value of the property
$('input').val();         // =>"newVal"    -value of the property
$('input').attr('value'); // =>"someValue" -value of the attr didn't change, since in this case it is not 1:1 mapping (change of the prop value doesn't reflect to the attribute value).

.data() 的情况

1) 获取方式:

- 请记住 attribute namedata-*property namedataset,所以:

1
<input type="checkbox" data-detail="somedata">
1
2
3
4
5
6
 $('input')[0].dataset; //=> [object DOMStringMap] { detail:"somedata"}
 $('input')[0].dataset.detail; // =>"somedata"
 $('input').prop('dataset'); //=>[object DOMStringMap] { detail:"somedata"}
 $('input').prop('dataset').detail; // =>"somedata"
 $('input').data('detail'); // =>"somedata"
 $('input').attr('data-detail');  //  =>"somedata"

2) 设置方法:

I) $('input').prop('dataset').detail='newData';

1
2
3
4
 $('input').prop('dataset');  //=> [object DOMStringMap] { detail:"newData"}
 $('input').prop('dataset').detail; // =>"newData"
 $('input').attr('data-detail'); // =>"newData"
 $('input').data('detail'); // =>"newData"

II) $('input').attr('data-detail','newData');

1
2
3
4
 $('input').prop('dataset');  //=> [object DOMStringMap] { detail:"newData"}
 $('input').prop('dataset').detail; // =>"newData"
 $('input').attr('data-detail'); // =>"newData"
 $('input').data('detail'); // =>"newData"

So you can see that here is 1:1 mapping, attr change reflects prop and
vice versa.

但是检查第三种方式:

III) $('input').data('detail','newData');

1
2
3
4
 $('input').prop('dataset'); // =>  [object DOMStringMap] { detail:"somedata"}
 $('input').prop('dataset').detail; // =>"somedata"
 $('input').attr('data-detail'); // =>"somedata"
 $('input').data('detail');  // =>"newData"    <-----******

那么,这里发生了什么?

$(elem).data(key, value) does not change the HTML5 data-* attributes
of the element. It stores its values in $.cache internally.

所以为了获得 data-* 你永远不会出错 .data() :

1
2
3
4
5
6
7
$(".saveBtn").on("click", function() {
    var saveBtn = $(this);
    var detail = saveBtn.data("detail");
    var relevantInput = saveBtn.parent().next();
    var value = relevantInput.prop("value");

});

  • 哇!谢谢你很详细的回答,我学到了很多。
  • 谢谢,比API的文档更有帮助

有关关于 javascript:jQuery .prop() 返回未定义,而 .attr() 对数据按预期工作-*的更多相关文章

  1. ruby - Facter::Util::Uptime:Module 的未定义方法 get_uptime (NoMethodError) - 2

    我正在尝试设置一个puppet节点,但ruby​​gems似乎不正常。如果我通过它自己的二进制文件(/usr/lib/ruby/gems/1.8/gems/facter-1.5.8/bin/facter)在cli上运行facter,它工作正常,但如果我通过由ruby​​gems(/usr/bin/facter)安装的二进制文件,它抛出:/usr/lib/ruby/1.8/facter/uptime.rb:11:undefinedmethod`get_uptime'forFacter::Util::Uptime:Module(NoMethodError)from/usr/lib/ruby

  2. ruby - 为什么 4.1%2 使用 Ruby 返回 0.0999999999999996?但是 4.2%2==0.2 - 2

    为什么4.1%2返回0.0999999999999996?但是4.2%2==0.2。 最佳答案 参见此处:WhatEveryProgrammerShouldKnowAboutFloating-PointArithmetic实数是无限的。计算机使用的位数有限(今天是32位、64位)。因此计算机进行的浮点运算不能代表所有的实数。0.1是这些数字之一。请注意,这不是与Ruby相关的问题,而是与所有编程语言相关的问题,因为它来自计算机表示实数的方式。 关于ruby-为什么4.1%2使用Ruby返

  3. ruby-on-rails - Rails 3.2.1 中 ActionMailer 中的未定义方法 'default_content_type=' - 2

    我在我的项目中添加了一个系统来重置用户密码并通过电子邮件将密码发送给他,以防他忘记密码。昨天它运行良好(当我实现它时)。当我今天尝试启动服务器时,出现以下错误。=>BootingWEBrick=>Rails3.2.1applicationstartingindevelopmentonhttp://0.0.0.0:3000=>Callwith-dtodetach=>Ctrl-CtoshutdownserverExiting/Users/vinayshenoy/.rvm/gems/ruby-1.9.3-p0/gems/actionmailer-3.2.1/lib/action_mailer

  4. ruby-on-rails - form_for 中不在模型中的自定义字段 - 2

    我想向我的Controller传递一个参数,它是一个简单的复选框,但我不知道如何在模型的form_for中引入它,这是我的观点:{:id=>'go_finance'}do|f|%>Transferirde:para:Entrada:"input",:placeholder=>"Quantofoiganho?"%>Saída:"output",:placeholder=>"Quantofoigasto?"%>Nota:我想做一个额外的复选框,但我该怎么做,模型中没有一个对象,而是一个要检查的对象,以便在Controller中创建一个ifelse,如果没有检查,请帮助我,非常感谢,谢谢

  5. ruby - 主要 :Object when running build from sublime 的未定义方法 `require_relative' - 2

    我已经从我的命令行中获得了一切,所以我可以运行rubymyfile并且它可以正常工作。但是当我尝试从sublime中运行它时,我得到了undefinedmethod`require_relative'formain:Object有人知道我的sublime设置中缺少什么吗?我正在使用OSX并安装了rvm。 最佳答案 或者,您可以只使用“require”,它应该可以正常工作。我认为“require_relative”仅适用于ruby​​1.9+ 关于ruby-主要:Objectwhenrun

  6. ruby - 检查字符串是否包含散列中的任何键并返回它包含的键的值 - 2

    我有一个包含多个键的散列和一个字符串,该字符串不包含散列中的任何键或包含一个键。h={"k1"=>"v1","k2"=>"v2","k3"=>"v3"}s="thisisanexamplestringthatmightoccurwithakeysomewhereinthestringk1(withspecialcharacterslike(^&*$#@!^&&*))"检查s是否包含h中的任何键的最佳方法是什么,如果包含,则返回它包含的键的值?例如,对于上面的h和s的例子,输出应该是v1。编辑:只有字符串是用户定义的。哈希将始终相同。 最佳答案

  7. ruby - 在 Ruby 中有条件地定义函数 - 2

    我有一些代码在几个不同的位置之一运行:作为具有调试输出的命令行工具,作为不接受任何输出的更大程序的一部分,以及在Rails环境中。有时我需要根据代码的位置对代码进行细微的更改,我意识到以下样式似乎可行:print"Testingnestedfunctionsdefined\n"CLI=trueifCLIdeftest_printprint"CommandLineVersion\n"endelsedeftest_printprint"ReleaseVersion\n"endendtest_print()这导致:TestingnestedfunctionsdefinedCommandLin

  8. ruby - 定义方法参数的条件 - 2

    我有一个只接受一个参数的方法:defmy_method(number)end如果使用number调用方法,我该如何引发错误??通常,我如何定义方法参数的条件?比如我想在调用的时候报错:my_method(1) 最佳答案 您可以添加guard在函数的开头,如果参数无效则引发异常。例如:defmy_method(number)failArgumentError,"Inputshouldbegreaterthanorequalto2"ifnumbereputse.messageend#=>Inputshouldbegreaterthano

  9. ruby - 如何在 Grape 中定义哈希数组? - 2

    我使用Ember作为我的前端和GrapeAPI来为我的API提供服务。前端发送类似:{"service"=>{"name"=>"Name","duration"=>"30","user"=>nil,"organization"=>"org","category"=>nil,"description"=>"description","disabled"=>true,"color"=>nil,"availabilities"=>[{"day"=>"Saturday","enabled"=>false,"timeSlots"=>[{"startAt"=>"09:00AM","endAt"=>

  10. ruby - 获取模块中定义的所有常量的值 - 2

    我想获取模块中定义的所有常量的值:moduleLettersA='apple'.freezeB='boy'.freezeendconstants给了我常量的名字:Letters.constants(false)#=>[:A,:B]如何获取它们的值的数组,即["apple","boy"]? 最佳答案 为了做到这一点,请使用mapLetters.constants(false).map&Letters.method(:const_get)这将返回["a","b"]第二种方式:Letters.constants(false).map{|c

随机推荐