Alerting Attribute Content
http://jsbin.com/uzogag/2/edit
I've attempted and searched for jQuery code that will alert "English" from the attribute selector. It's simple a newbie questions, but a good exercise. Would some kind soul lend wisdom?
JavaScript
$('p[language]').alert(this.text());
HTML
开发者_JAVA技巧<!DOCTYPE html>
<html>
<head>
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<meta charset=utf-8 />
<title>JS Bin</title>
<!--[if IE]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
</head>
<body>
<h1>Select elements with specific text:</h1>
<div>
<p>This is paragraph 1.</p>
<p language="English">This is paragraph 2.</p>
<p>This is paragraph 3.</p>
<p>This is paragraph 4.</p>
</div>
<form>
<input type="button" value="Select" onclick="setStyle()"></input>
</form>
</body>
</html>
jQuery object's do not have an alert
method. Do this instead:
alert($('p[language]').attr('language'));
The selector p[language]
will find the <p>
element that has a language
attribute.
The attr
method returns the value of the attribute, in this case, "English". If the selector matched more than one element, this method will retrieve the value of the first match.
The alert
method is a global function (i.e. it's a member of the window
object).
Try this:
$('p[language]').click( function() {
alert($(this).attr('language'));
} );
Native JavaScript method alert
is not chainable with jQuery objects.
alert($('p[language]').attr('language'))
精彩评论