4

我是 jquery 的新手。我知道这个问题很愚蠢,但我在这里遗漏了一些概念。这是问题所在:

$("input.integers").each(function(index) {

    console.log("----");
    console.log($(this).attr('id') + " " + $(this).val()); 
    console.log($(this).attr('id') + " " + $("#"+$(this).attr('id')).val());
    // the next log is here just to show a direct selection. I'm concerned about the two logs above this one 
    console.log($("#myId").attr('id'), $("#myId").val());

    that.setModelData($(this).attr('id'), $(this).val());
});

这是输出:

PhantomJS 1.6 (Linux) LOG: '----'
PhantomJS 1.6 (Linux): Executed 61 of 90
PhantomJS 1.6 (Linux) LOG: 'myId '
PhantomJS 1.6 (Linux): Executed 61 of 90
PhantomJS 1.6 (Linux) LOG: 'myId 123'
PhantomJS 1.6 (Linux): Executed 61 of 90
PhantomJS 1.6 (Linux) LOG: [ 'myId', '123' ]

标签是输入。为什么$(this).val()是空的并且$("#"+$(this).attr('id')).val()包含正确的值?

更新:

业力测试:

it('the model must be updated', function(){

    $("#myId").val("123");  

    $("#save-process").click();
    server.respond();

    expect(fdtView.model.get('myId')).toBe("123");

});

夹具:

<input id="myId" name="myId"
    class="integers" type="text" /> 
4

2 回答 2

0

好的,我不得不说这是 karma 的问题,而不是 jquery 的问题。

我们正在使用 Backbone.js,视图正在加载视图定义中的模板:

template : _.template($("#mytemplate").html()),

Karma 在加载测试时如果找不到固定装置会进入异常,所以我们在一个名为 fixtures.js 的文件中添加了启动时的固定装置:

loadFixtures('viewtemplate.html','mytemplate.html');

(@Blame)有人在beforeEachjasmine 测试套件中添加了以下代码:

beforeEach( function() {
    loadFixtures('currentStepContainerFixture.html', 'mytemplate.html');

所以固定装置被加载了两次

当我在我的代码中使用时:

 console.log($(this).attr('id') + " " + $(this).val()); 
 console.log($(this).attr('id') + " " + $("#"+$(this).attr('id')).val());

基本上,第一个日志是关于当前元素的,而第二个日志是关于具有该 id 的第一个输入的。

这就是为什么我们有这种奇怪的行为。我不得不说,为存在具有相同 id 的两个元素而引发的某种异常会很有帮助

PhantomJS 1.6 (Linux): Executed 61 of 90
PhantomJS 1.6 (Linux) LOG: 'myId ' --> current $(this)
PhantomJS 1.6 (Linux): Executed 61 of 90
PhantomJS 1.6 (Linux) LOG: 'myId 123' --> first occurrence of "#myId"

这四点我不配,问题出在显示器和键盘之间。对不起 :(

于 2013-08-02T12:44:01.950 回答
0

在你的循环中,与 $("input.integers") 选择器匹配。所以,jquery 在内存中有这个选择器。$("#myId") 是一个唯一的选择器,对于每个循环,jquery 搜索这个元素并分析它。这两个元素相同只是巧合,因为您的 html 代码是:

<input class="integers" id="myId" />

但是,如果您有许多具有相同 CSS 类的输入,则情况会有所不同。

具有多个输入的示例。

HTML 代码:

<input class="integers" value="toto"/>
<input class="integers" value="titi"/>
<input class="integers" value="tata"/>
<input class="integers" value="tutu"/>

JS代码:

$("input.integers").each(function(index) {
console.log("Value = "+$(this).val);
}

控制台日志:

Value = toto
Value = titi
Value = tata
Value = tutu

所以回答你的问题,如果this.val()不同的$("#"+$(this).attr('id')).val())是加载这个的选择器不好。

于 2013-08-02T10:21:40.903 回答