所以我一直在尝试使用 Javascript 创建一个 slug,并允许我的用户在按下提交之前查看该 slug 是什么。这是我的 Javascript 代码:
function slugify(text) {
return text
.toString() // Cast to string
.toLowerCase() // Convert the string to lowercase letters
.normalize('NFD') // The normalize() method returns the Unicode Normalization Form of a given string.
.trim() // Remove whitespace from both sides of a string
.replace(/\s+/g, '-') // Replace spaces with -
.replace(/[^\w\-]+/g, '') // Remove all non-word chars
.replace(/\-\-+/g, '-'); // Replace multiple - with single -
}
function listingslug(text) {
document.getElementById("slug").value = slugify(text);
}
这是我正在使用的 html,它使用 Bootstrap 4:
<form class="form">
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" onkeyup="listingslug(this)" id="name" name="name" placeholder="Example input placeholder">
</div>
<label for="slug">Your vanity URL</label>
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text" id="basic-addon3">{{ env('APP_URL') }}/listing/</span>
</div>
<input type="text" class="form-control" id="slug" name="slug" aria-describedby="basic-addon3">
</div>
</form>
我收到一条错误消息,指出listingslug 不存在。我正在使用 Laravel mix 来编译我的代码。我做错了什么?
您只需将
onkeyup="listingslug(this)"
更改为 oninput="listingslug(this.value)"
function slugify(text) {
return text
.toString() // Cast to string
.toLowerCase() // Convert the string to lowercase letters
.normalize('NFD') // The normalize() method returns the Unicode Normalization Form of a given string.
.trim() // Remove whitespace from both sides of a string
.replace(/\s+/g, '-') // Replace spaces with -
.replace(/[^\w\-]+/g, '') // Remove all non-word chars
.replace(/\-\-+/g, '-'); // Replace multiple - with single -
}
function listingslug(text) {
document.getElementById("slug").value = slugify(text);
}
<form class="form">
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" oninput="listingslug(this.value)" id="name" name="name" placeholder="Example input placeholder">
</div>
<label for="slug">Your vanity URL</label>
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text" id="basic-addon3">{{ env('APP_URL') }}/listing/</span>
</div>
<input type="text" class="form-control" id="slug" name="slug" aria-describedby="basic-addon3">
</div>
</form>