2012-05-11 53 views
1

我似乎無法在jQuery中的選擇器中使用變量。這是一個非常簡單但煩人的錯誤!一個例子來看看這個jsFiddle選擇器jQuery中的變量

下不起作用:

var folder_id = "folder"; 

$("#selects select[name='" + folder_id + "']").append('<span>Hi></span>'); 

標記:

<div id="selects"> 
    <select name="folder_id"> 
     <option>hey</option> 
    </select> 

</div>​ 
+3

始終在問題本身中包含所有相關代碼**和**標記,而不僅僅是一個鏈接:http://meta.stackexchange.com/questions/118392/add-stack-overfow-faq這個問題的入口或類似代碼我已經爲你添加了小提琴的標記。 –

回答

2

回答你實際上問的問題(但也請看下面):

你告訴它找到一個selectnamefolder,而不是folder_id。但是您的select的名稱爲folder_id

因此,要麼更改代碼:

//      v----- change here 
var folder_id = "folder_id"; 

$("#selects select[name='" + folder_id + "']").append('<span>Hi></span>'); 

Updated fiddle(但再次,請參閱下面的下破)

... 變化的標記:

<div id="selects"> 
    <select name="folder"> 
     <option>hey</option> 
    </select> 

</div>​ 

Updated fiddle


但請注意,您正試圖將span附加到select,這是無效的標記,並且不起作用。 select elements不能包含spans(只有optionoptgroup元素)。如果你打算把它select後,使用after

//            v--- change here 
$("#selects select[name='" + folder_id + "']").after('<span>Hi></span>'); 
//   also note the `>` you probably don't want here ----^ 

Another fiddle

1
var folder_id = "folder_id"; 

$("#selects select[name='" + folder_id + "']").append('<span>Hi</span>'); 

您的ID設置不正確,再加上一些HTML是跨度被追加不正確。

1

除了其他人的回答,哪些是正確的,爲什麼要將<span>添加到<select>列表中?

當然,如果你想添加一個新的選項,你應該添加這樣的東西?

$("#selects select[name='" + folder_id + "']").append('<option>Hi</option>'); 

這將在選擇列表中添加一個新選項,請參閱this小提琴。


或者,如果您嘗試將文本添加到選項列表,爲什麼不是這樣?

$("#selects select[name='" + folder_id + "'] option").append('<span>Hi</span>'); 

請參閱this小提琴。

0

看到我更新的(工作)例如:

http://jsfiddle.net/yYzvL/6/

有你的代碼的幾個問題:

1 - 分配給folder_id
2不正確的值 - 不使用值<option>標籤您正在追加

更新的JavaScript是:

var folder_id = "folder_id"; 
$('#selects select[name="' + folder_id + '"]').append($('<option>Hi</option>'));