2016-01-20 88 views
2
$('#modal').append('<input type="hidden" value="' + $('#selector').val() || myVar + '">'); 

什么会导致我上面的append不起作用?在它的下一行,我做append("test"),它的工作。我的控制台中没有错误。jQuery追加不按预期工作

回答

3

您需要使用括号,这样or操作符才会考虑附加到$('#selector').val()而不是input。试试这个:

$('#modal').append('<input type="hidden" value="' + ($('#selector').val() || myVar) + '">'); 
+0

下面是操作的Javascript为了一个有用的资源:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence正如你可以看到||和&&低于+, - ,*和/。 – VKK

+0

哇它的工作,但为什么? –

0

创建input和值分开,然后调用append?

var inputValue = $('#selector').val() || myVar; 
var $input = $("<input>", {"type": "hidden", "value": inputValue }); 
$('#modal').append($input);