2012-11-16 134 views
1

我相信我的jQuery問題很簡單,這讓我瘋狂,我無法得到它。jQuery語法不設置對象屬性

我有一個屬性爲「content」的對象,我希望能夠接受該對象,使用jQuery處理屬性「content」,然後用jQuery創建的新值覆蓋該值。

例子:

o.content = "<div><span>hello</span></div>"; 
$('div', o.content).addClass('test'); 

在這一點上我想o.content等於<div class='test'><span>hello</span></div>

我不能爲我的生活出的語法。任何幫助真的很感激。

+0

很難說出你想要做什麼,請重新翻譯。你認爲'$('div',param)'的第二個參數有什麼作用?見http://api.jquery.com/jQuery/ –

+1

所以你想要一個HTML字符串或jQuery對象? – Musa

回答

1

docs of the jquery functioncontext必須是

DOM元素,文檔,或jQuery來作爲上下文

你的上下文(o.content)是一個字符串使用。另外,jQuery函數不能選擇整個上下文,它只能選擇該上下文中的元素。

試試這個:

// make o.content a jquery element, not a string 
o.content = $("<div><span>hello</span></div>"); 

// select on something inside the context (inside the div), not the div itself 
$('span', o.content).addClass('test'); 

http://jsfiddle.net/JfW4Q/

2

解析HTML中o.content,添加類,解析HTML附加到一個新的<div>,並獲得新的div的HTML:

o.content = "<div><span>hello</span></div>"; 
var el = $(o.content).addClass('test'); 
o.content = $("<div>").append(el).html(); 

編輯:這是假設你想o.content仍包含一個字符串,而不是一個jQuery對象。在這種情況下,它更簡單:

o.content = $(o.content).addClass('test'); 
+0

這可能是OP想要的,你有水晶球嗎? –

+0

@JuanMendes - 他說他希望'o.content'從''

hello
''變成''
hello
「'。這樣做。也就是說,假設他想要一個字符串而不是一個jQuery對象。如果[Musa的評論](http://stackoverflow.com/questions/13424145/jquery-syntax-not-setting-object-property#comment18346763_13424145)已解決,我們會發現。 – gilly3

+0

幹得好@gilly3。這完全是我想要的。謝謝! –

1

我不認爲你可以從這樣的字符串查找元素..我寧願不喜歡它的下方,

var content = "<span>hello</span>"; 
content = $('<div/>', {class: 'test'}).html(content) 

DEMO:http://jsfiddle.net/k4e5z/

2

這會給你一個字符串<div class="test"><span>hello</span></div>如果這是你想要的東西:

$(o.content).addClass('test').wrap('<div>').parent().html(); 
1

你想下面

o.content = "<div><span>hello</span></div>"; 
// Create a jQuery object you can call addClass on 
var docFragment = $(o.content); 
docFragment.addClass('test'); 
// Since there's no outerHTML in jQuery, append it to another node 
var wrapper = $('div'); 
docFragment.appendTo(wrapper); 
// The HTML of the wrapper is the outerHTML of docFragment 
console.log(wrapper.html()); // outputs <div class='test'><span>hello</span></div> 
1

爲什麼沒有把一切都在同一行:

var o = {}; 
o.content = $("<div></div>")  // create element 
    .addClass('test')    // add class 
    .html('<span>hello</span>'); // append content 

小提琴:http://jsfiddle.net/kboucher/eQmar/

1
o.content = $("<div><span>hello</span></div>"); 
o.content.addClass('test'); 

o.content是本例中的一個jQuery對象,與僅僅是一個字符串相反。以下是jsfiddle上的演示:http://jsfiddle.net/cvbsm/1/