【问题标题】:Search and replace option element in string JQuery在字符串 JQuery 中搜索和替换选项元素
【发布时间】:2014-06-27 09:05:28
【问题描述】:

我有下一个字符串变量,其中包含下一个字符串

var content = '<div id="TypeModifiedProduct" class="form-group WSUage2">
  <label for="TypeModified">Type</label>
  <span class="pull-right alignText" style="margin-right: 40%;">
    <input type="checkbox" id="UseTypeModified" name="UseTypeModified" > Use option
  </span>
  <select name="TypeModified" id="TypeModified" class="form-control" style="width:40%" >
    <option value="Maintenance - Stand Alone form" >Maintenance - Stand Alone form</option>
    <option value="Maintenance Plus - Stand Alone form">Maintenance Plus - Stand Alone form</option>
  </select>
</div>';

现在我想搜索第二个选项

<option value="Maintenance Plus - Stand Alone form">Maintenance Plus - Stand Alone form</option>

并将其更改为已选择的选项

<option value="Maintenance Plus - Stand Alone form" selected >Maintenance Plus - Stand Alone form</option>

然后最后返回这个带有选项元素变化的新字符串。

感谢您的建议

【问题讨论】:

  • 试试var $div = $('&lt;div /&gt;',{html: content}); $div.find('option[value="Maintenance Plus - Stand Alone form"]').attr('selected', 'selected'); content = $div.html()

标签: jquery html search replace


【解决方案1】:

因为你正在寻找一个字符串作为结果

var $div = $('<div />',{html: content});
$div.find('option[value="Maintenance Plus - Stand Alone form"]').attr('selected', 'selected');

content = $div.html();

console.log(content)

演示:Fiddle

【讨论】:

  • 感谢大家的帮助,现在我希望全文包含所选选项,Arun 谢谢,但我需要整个文本以及您在小提琴中所做的更改
  • @martinezjc 因为我们正在分配content = $div.html();content 将有修改后的文本
  • 对不起,我没有看到整个控制台 Arun,非常感谢大家的回答!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-09
  • 2017-01-10
相关资源
最近更新 更多