【发布时间】:2019-08-18 14:02:10
【问题描述】:
我正在尝试从 href 属性中获取 url 并附加并返回它,但我不断收到“无法读取 null 的属性 'href'”。
我尝试使用 document.getElementsByClassName("CLASS").href 获取值,但返回未定义,然后当我使用 id 时,我得到上面的 null 错误。
这是我的 HTML:
<a class="js-link-name" id="js-link" href="{{ route('report.file.list')}}">Click Me</a>
@push('scripts')
<script>
$(function () {
var questionnaires = [];
@foreach($vm->getQuestionnaires() as $questionnaire)
questionnaires.push(new window.app.locationReports.Questionnaire('{{ $questionnaire->getValue() }}', '{{ $questionnaire->forDisplay() }}'));
@endforeach
new window.app.locationReports.LocationTiles($('.js-location-tiles'), $('.js-file-download-link'), $('.js-legend-trigger'), '{{ $vm->getUserViewPreferenceValue() }}', questionnaires, '{{ route('api.v1.reports.customer-satisfaction.recommend-to-others') }}', '{{ route('report.customer-satisfaction.locations.data.view-preference') }}');
});
</script>
@endpush
这是我的 JS 函数:
buildLocationReportListUrl(){
let newUrl = URI(document.getElementById('js-link').href).addSearch(this.locationId);
return newUrl;
}
【问题讨论】:
-
该函数何时运行?
-
@Herohtar 我在控制台中调用它。一旦我让它工作,我将创建一个单独的函数,将新 URL 添加到 href 属性。
-
对我来说很好:jsfiddle.net/khrismuc/r8qdfjxc 请创建一个minimal reproducible example,以便我们重现您遇到的错误。该错误清楚地指向在
<a>存在之前运行的脚本。 -
在您的脚本标签中添加
defer以确保 -
@ChrisG 我相信你是对的。我添加了一些代码,以便您帮助我了解问题所在。
标签: javascript laravel routes href