这是我用来尝试从导航中获取所有href的代码:
componentDidMount(){
$("nav ul li a").each(function(k, j){
console.log(j);
});
}
由此我成功地将所有dom元素打印在控制台上:
<a href="#home" class="nav-link">Home</a>
<a href="#about" class="nav-link">About</a>
...etc...
现在尝试实际拔出href字符串,我尝试了许多事情,例如尝试console.log(j.attr('href'))
(在上面显示的循环中),但还没有任何工作。 (TypeError:j.attr不是函数)
我应该为此使用什么?而且我的应用程序是在ReactJS中构建的,所以我想知道是否有更合适的方法来实现这一点,例如refs
非常感谢
答案 0 :(得分:0)
如果你想摆脱使用j.href切割的字符串,你甚至可以在j上使用getAttribute。
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#home" class="nav-link">Home</a>
<a href="#about" class="nav-link">About</a>
########## GENERAL CONFIGURATION
TIME_ZONE = 'America/Argentina/Cordoba'
LANGUAGE_CODE = 'es-ES'
SITE_ID = 1
USE_I18N = True
USE_L10N = True
USE_TZ = True
########## END GENERAL CONFIGURATION
########## SOCIALACCOUNT CONFIGURATION
SOCIALACCOUNT_EMAIL_VERIFICATION = 'optional'
SOCIALACCOUNT_QUERY_EMAIL = True
SOCIALACCOUNT_AUTO_SIGNUP = True
SOCIALACCOUNT_EMAIL_REQUIRED = True
SOCIALACCOUNT_PROVIDERS = \
{'facebook':
{'SCOPE': ['email',],
'AUTH_PARAMS': {'auth_type': 'reauthenticate'},
'METHOD': 'js_sdk',
'LOCALE_FUNC': lambda request: 'es-ES',
'VERIFIED_EMAIL': True}}
ACCOUNT_AUTHENTICATION_METHOD = "username_email"
ACCOUNT_EMAIL_REQUIRED = True
ACCOUNT_EMAIL_VERIFICATION = "optional"
ACCOUNT_UNIQUE_EMAIL = True
ACCOUNT_USERNAME_REQUIRED = True
ACCOUNT_USERNAME_MIN_LENGTH = 5
ACCOUNT_PASSWORD_MIN_LENGTH = 6
ACCOUNT_LOGIN_ON_EMAIL_CONFIRMATION = True
ACCOUNT_SIGNUP_FORM_CLASS = 'algo.forms.SignupForm'
########## END SOCIALACCOUNT CONFIGURATION
答案 1 :(得分:0)
这是一个有效的解决方案。希望它有所帮助!
$("a").each(function(){
console.log($(this).attr("href"));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<a href="#home" class="nav-link">Home</a>
<a href="#about" class="nav-link">About</a>
答案 2 :(得分:0)
代码中的一行更改
$("nav ul li a").each(function(k, j){
console.log($(this).attr('href'));
});
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<nav class="navbar navbar-default">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="#">WebSiteName</a>
</div>
<ul class="nav navbar-nav">
<li class="active"><a href="home">Home</a></li>
<li><a href="page1">Page 1</a></li>
<li><a href="page2">Page 2</a></li>
<li><a href="page3">Page 3</a></li>
</ul>
</div>
</nav>