获取outerHTML代码问题

时间:2015-06-02 11:32:40

标签: javascript jquery

这是我的js代码:

function myfunction(){
    $("#label_startDate[0]")[0].outerHTML;
}

这是html部分:

<label id="label_startDate[0]" class="" style="">
    <span id="star_startDate[0]" style="display: none; color: red">*</span>
    <input name="startDate[0]" id="startDate[0]" value="2015-06-02" readonly="" class="forDatePicker hasDatepicker" size="14" onchange="changeEndDate(0); calculateDaysDuration('@[0]', 0); "type="text">
</label>

由于我从标签中获得了奇怪的id格式,我无法获得outerHTML。我该怎么办 ?我无法更改ID label_starDate [0]

1 个答案:

答案 0 :(得分:6)

使用\\转义[]并使用.prop()访问属性

 $("#label_startDate\\[0\\]").prop("outerHTML");

来自Docs

  

使用任何元字符(例如!“#$%&amp;'()* +,。/:;&lt; =&gt;?@ [] ^`{|}〜)作为文字作为名称的一部分,必须使用两个反斜杠进行转义:\\。

$(function() {
    alert( $("#label_startDate\\[0\\]").prop("outerHTML"))
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label id="label_startDate[0]" class="" style="">
                        <span id="star_startDate[0]" style="display: none; color: red">*</span>
                        <input name="startDate[0]" id="startDate[0]" value="2015-06-02" readonly="" class="forDatePicker hasDatepicker" size="14" onchange="changeEndDate(0); calculateDaysDuration('@[0]', 0); "type="text">  
</label>