【问题标题】:outerHTML and attribute updatesouterHTML 和属性更新
【发布时间】:2014-01-30 13:37:33
【问题描述】:

我正在尝试将 HTML 代码作为属性更新的字符串获取。

我有一个 select 标记,我使用 JavaScript 更新其选项。

默认情况下,第一个optionselected,使用HTML 属性selected="selected"

如果我使用option1.selected = false 从第一个选项中取消设置selected,并为第二个option 设置option2.selected = true,然后调用outerHTMLselect,我会得到

<select>
    <option selected="selected">one</option>
    <option>two</option>
    <option>three</option>
  </select>

如您所见,selected 属性仍在第一个option 上,而它已移至第二个option。预期结果是

<select>
    <option>one</option>
    <option selected="selected">two</option>
    <option>three</option>
  </select>

这是一个示例http://jsbin.com/adAbAMe/2/edit?html,js,console,output(单击run with js 以获取结果),它表明如果selected 属性已更改,它不会在HTML 代码中更改。

但是我需要通过成功的属性更新从 outerHTML 中获取最终的 HTML,因为如果我将这个 select 移动到某个地方,我将不会得到我在使用 JavaScript 之前所做的任何更新。

是否有任何方法可以将 HTML 作为具有真实属性值的字符串?

【问题讨论】:

  • 属性selected仅用于设置初始值,之后所做的任何更改都会反映在属性中
  • 一个解决方案是编写一个更改处理程序来更新属性
  • 嗯,jsbin 实际上是为我工作的,哈哈

标签: javascript jquery html select outerhtml


【解决方案1】:

selected 属性不会自动更新,但您可以将其设置为将其删除并添加到适当的元素中。

//remove "selected" from first
if (i==0) {
  option.selected = false;
  option.removeAttribute("selected");
}

//add "selected" to second
if (i==1) {
  option.selected = true;
  option.setAttribute("selected", "selected");
}

Here's a working fiddle.

【讨论】:

    【解决方案2】:

    你可以使用

    option.setAttribute('selected', 'selected');
    

    option.removeAttribute('selected');
    

    【讨论】:

      【解决方案3】:

      试试

      $('button').click(function () {
          console.log($('select').prop('outerHTML'))
      })
      
      $('select').change(function(){
          $(this).find('option[selected]').removeAttr('selected');
          $(this).find('option:selected').attr('selected', 'selected');
      })
      

      演示:Fiddle

      【讨论】:

        【解决方案4】:

        来自DOM Specification

        selected 类型为 boolean

        在交互式用户代理中表示相应表单控件的当前状态。更改此属性会更改表单控件的状态,但不会更改元素的 HTML selected 属性的值。

        (强调我的)

        要获得您想要的效果,您需要option.setAttribute('selected', 'selected'),但在其他选项中您还需要option.removeAtrribute('selected')

        【讨论】:

          猜你喜欢
          • 2023-03-17
          • 1970-01-01
          • 2015-12-15
          • 1970-01-01
          • 1970-01-01
          • 2013-05-02
          • 2010-11-24
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多