내가 유효한 HTML로 작성된 속성의 문자열을 가지고, 나는 실제 HTML 요소 (안 요소의 HTML 문자열)에 이러한 속성을 넣어하려는 속성을.html로 요소
예를 들어, 변수 이름이 attributesStr
인 민감한 문자열이 있는데이 속성을 #htmlElement
div에 추가하려고합니다.
<div id="htmlElement" class='regularClass' title='Title... with spaces!' style='color: red; font-weight: bold;' data-attributenovalue>
The HTML element!
</div>
이 어떻게 자바 스크립트 또는 jQuery를이 작업을 수행 할 수 있습니다처럼
JQuery와/자바 스크립트 코드가 실행 된 후var attributesStr = "";
attributesStr += " class='regularClass'"; // Needs to handle key value attributes.
attributesStr += " title='Title... with spaces!'"; // And attributes with spaces.
attributesStr += " style='color: red; font-weight: bold;'"; // And style with multiple properties.
attributesStr += " data-attributenovalue"; // And attributes with no value.
// Your special code to add the attributes to `#htmlElement` goes here.
<div id="htmlElement">
The HTML element!
</div>
, #htmlElement
이 보일 것입니다?
첫 번째 시도 : 나는 공간에 attributesStr
을 보내고 .split()
으로 내가 이것을 할 수있는 생각하고 =
에 각각의 속성 키 값 쌍을 분할하고, 한 후 반복하는 그 배열과 각 키 값 쌍을 추가하는 jQuery의 .prop()
또는 .attr()
하지만,이 두 가지 이유로 작동하지 않을 것이다 : 그들은 공간을 가지고 있기 때문에
- 그것은
style
및title
속성에 실패합니다. - 일 수도 있습니다.은 값이없는 속성에서 작동하지 않습니다.
'attributesStr.match (/ [^ \ S =] + (= '] [^'] *는 '])?/g)'이렇게하면 첫 번째 분할 얻을 – tallberg
미리 만들어진 문자열을 해킹하여 필요한 것보다 더 어렵게 만듭니다. 해당 문자열을 작성한 시점에 스타일을 적용 할 수 있습니까? 또는 나중에 적용 할 값이있는 객체를 만들 수도 있습니다. –
@RoryMcCrossan 이미 원래의 문제에 대한 다른 해결책을 찾았습니다. JS/JQuery에서이 작업을 수행 할 수있는 방법이 있는지 궁금했습니다. –