admin管理员组

文章数量:1290991

I need to show for every link, dynamically some text with Java-Script (jQuery). The problem is that the text is also formatted as HTML, so this causes some problems in the later view. Now I am storing it in the ID-attribute, this works, but only without embedded HTML in it.

<?php
...
$desc = '<p style="color: red">some <span>data</span></p>';
echo '<a href="#" id="' . $desc . '">' . $key . '</a>';
?>

Ajax-requests are not allowed. Is there a simple way to reach this goal?

I need to show for every link, dynamically some text with Java-Script (jQuery). The problem is that the text is also formatted as HTML, so this causes some problems in the later view. Now I am storing it in the ID-attribute, this works, but only without embedded HTML in it.

<?php
...
$desc = '<p style="color: red">some <span>data</span></p>';
echo '<a href="#" id="' . $desc . '">' . $key . '</a>';
?>

Ajax-requests are not allowed. Is there a simple way to reach this goal?

Share Improve this question asked Jun 17, 2012 at 17:47 user1462148user1462148 433 bronze badges 2
  • 2 The answer is simple: Don't do it. HTML markup contains tons of stuff that is not allowed in an ID. – ThiefMaster Commented Jun 17, 2012 at 17:49
  • 1 This is serious abuse of the id attribute – sczizzo Commented Jun 17, 2012 at 17:49
Add a ment  | 

2 Answers 2

Reset to default 13

The id attribute is one of the least appropriate places for this (must be unique, cannot contain all characters). Use a data- attribute (introduced in HTML5 but also works in old browsers and without using a HTML5 doctype) instead:

<a href="#" data-desc="....">

If you are using jQuery you can access it via .data('desc'), in plain JavaScript the most portable way is using .getAttribute('data-desc'). If you do not need to support older browsers, you can access the value via the .dataset.desc property.

In any case, you need to ensure that nothing breaks when inserting dynamic data in the attribute. Use htmlspecialchars() for this purpose:

$desc = '<p style="color: red">some <span>data</span></p>';
echo '<a href="#" data-desc="' . htmlspecialchars($desc) . '">' . $key . '</a>';

The other ments are absolutely right. Don't do this. It isn't appropriate to put anything but an identifier of some kind in the id attribute.

That being said, I figured I would let you know why your code is failing. You need to use htmlspecialchars() on your data before you try to use it as you intend. That way, HTML won't be interpreted as HTML... all of the HTML entities will get converted for, so your attribute value is interpreted as text. < bees &lt;, > bees &gt; and so on. If you later pull the value out (with jQuery or whatever), you will get the text as intended.

本文标签: javascriptHow to store HTMLMarkup in the IDAttributeStack Overflow