jQuery ပြောင်းလဲခြင်း - contents() အမိန့်

အကျိုးသတ္တု

ပုဒ်များ အတွင်း အချင်း များ အား တွေ့ရှိပြီး အကြောင်းဝင် အချင်း များ ကို အကြယ်အဖြူ လက္ခဏာ ဖြင့် ကိုက်ယူသည်。

$("p").contents().filter(function(){ return this.nodeType != 1; }).wrap("<b/>");

亲自试一试

အသုံးပြုခြင်း နှင့် အသုံးချခြင်း

contents() အမိန့် ပေါ်တွင် အဆိုအရာ များ အဖွဲ့ အား ပုဂ္ဂိုလ်အချင်း များ အဖွဲ့ အတွင်း အရေးသူ အပိုင်းအခွဲ များ ကို ရယူပြီး အကြောင်းဝင် အချင်း များ နှင့် အစားအရေးသူ အချင်း များ ကို ပါဝင်စေသည်。

အပြောအရာ

.contents()

အသေးစိတ်ဖော်ပြချက်

အခွက် ပေါ်တွင် အကိုရိုးမူလ ဒီမိုကရေစီ အဆိုအရာများ ကို ကိုက်ယူသော jQuery အပျက်အလုပ် အား ဒီ .contents() အမိန့် က ဒီ ဒီမိုကရေစီ အပျက်အလုပ် မှ ဒီ အဆိုအရာ များ အပိုင်းအခွဲ များ ကို တွေ့ရှိနိုင်သည်။ .contents() နှင့် .children() 方法类似,不同的是前者在结果 jQuery 对象中包含了文本节点以及 HTML 元素。

.contents() 方法也可以用于获得 iframe 的内容文档,前提是该 iframe 与主页面在同一个域。

请思考下面这个带有一些文本节点的

,每个节点被两个折行元素 (
) 分隔:

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.

我们可以使用 .contents() 方法来把文本块转换为形式良好的段落:

$('.container').contents().filter(function() {
  return this.nodeType == 3;
})
  .wrap('

') .end() .filter('br') .remove();

亲自试一试

这段代码首先会接收

的内容,然后滤过其文本节点,将文本节点封装入段落标签中。这是通过测试元素的 .nodeType 属性实现的。该属性存有指示节点类型的数字代码;文本节点使用代码 3。内容会被再次过滤,这次针对
元素,这些元素会被移除。